【发布时间】:2019-04-15 11:04:36
【问题描述】:
我很难理解为什么下面的代码会抛出 Unhandled Promise Rejection 警告:
router.post('/stampaClasse/:as(20[0-9][0-9]/[0-9][0-9])/:classe([1-8])',async function (req,res,next){
const sezioni = await Classi.getSezioniFromAnnoScolasticoAndClasse(req.params.as,req.params.classe);
let options = {
semestre: req.body.semestre,
fontSize: req.body.fontSize,
textColor: '#515151',
gridColor: '#bec0be',
corDidattico:{
titolo:'prof.',
nome:'Roberto',
cognome:'Dalema'
}
}
let newPDF = new pdfKit();
try{
for(sezione of sezioni){
const idStudentiPromise = Classi.getStudentiFromAnnoScolasticoAndClasseAndSezione(req.params.as,req.params.classe,sezione)
const materiePromise = Classi.getMaterieSezione(req.params.as,req.params.classe,sezione)
const infoStudentiPromise = Promise.all( Studenti.getInfoStudentiById(await idStudentiResults) )
let classe = {
annoScolastico: req.params.as,
classe : req.params.classe,
sezione: sezione,
materie: await materiePromise,
studenti: await infoStudentiPromise
}
for(studente of classe.studenti){
studente.pagelleMateriePromises = classe.materie.map(async m=>Pagelle.getPagellaFromStudente(classe.annoScolastico,classe.classe,classe.sezione,m,studente.id));
}
for(studente of classe.studenti){
studente.pagelleMaterie = await Promise.all(studente.pagelleMateriePromises)
addHeader(newPDF,studente,classe,options);
addPagelleSemestre(newPDF,studente,classe,options);
addFooter(newPDF,studente,classe,options);
}
}
newPDF.pipe(res);
newPDF.end();
}
catch(err){
next(err)
}
});
错误出现多次,是因为在行
const infoStudentiPromise = Promise.all( Studenti.getInfoStudentiById(await idStudentiResults) )
idStudentiResults 已经返回一个 Promise.all()
不管是什么导致了错误,我想知道为什么它说错误没有被处理。 try catch 还不够吗?
【问题讨论】:
-
Promise.all 接受一组 promise 并在 then 块中解析它们。看看这个,它可能会有所帮助:developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
-
嗨!请使用tour,环顾四周,并通读help center,尤其是How do I ask a good question?,我还要查看Jon Skeet's question checklist 和Writing the Perfect Question。请使用 minimal reproducible example 来更新您的问题,以展示问题,最好是使用 Stack Snippets(
[<>]工具栏按钮;here's how to do one)可运行。 -
你已经说
Module.getInfo(ids)返回一个promise,而不是一个数组。如果这是真的(显示我们会更好),那你为什么要把它传递给Promise.all?这似乎没有任何意义...... -
why it is saying the error is unhandled因为错误未处理。一个普通的try / catch是无法捕捉到promise 错误的,除非你使用了async / awat,并且做了await Promise.all() -
你为什么要用承诺包装承诺
标签: javascript node.js express promise