【问题标题】:Unhandle Promise rejection inside try blocktry 块内未处理的 Promise 拒绝
【发布时间】: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 还不够吗?

【问题讨论】:

标签: javascript node.js express promise


【解决方案1】:

Promise.all 需要接收一系列承诺作为参数。确保 Module.getInfo(ids) 正在返回它。

【讨论】:

  • 也许可以分享Module.getInfo 的代码并告诉我们您想要实现的具体目标是什么
  • 我知道错误在哪里,但我不知道为什么它说错误未处理
  • 这一行没有任何承诺:const infoPromise = Promise.all( Module.getInfo(ids) );
  • 如果代码执行一些异步操作,你的意思是我需要为每一行代码添加一个 try-catch 块吗?
  • @FilippoBosco 不是 try-catch 块,而是 Promises 的 .catch 方法
猜你喜欢
  • 2019-02-28
  • 2017-11-20
  • 2018-03-19
  • 1970-01-01
  • 2016-11-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多