使用Node.js中的嵌套承诺处理错误

当嵌套的promise块中发生错误时,需要在最后一个外部catch块中捕获所有错误。

let docs = {
  total: 0,total_downloaded: 0,plan_type: null,};

Document.findAll({
  where: {
    report_request_id: req.params.requestId
  },attributes: ["id","folder_name","total_file"],})
  .then(documents => {
    documents.forEach(document => {
        docs.total += 1;

        if (document.get("status") == 1) {
          docs.total_downloaded += 1;
        }
    });
  })
  .then(function() {
    Request.findOne({
      where: {
        id: req.params.requestId
      }
    })
      .then(request => {
        //Suppose I got error here
        docs.plan_type = request.plan_type;
      })
      .catch(err => {
        // Block A
        throw err;
      });
  })
  .then(function() {
    res.status(200).send(docs);
  })
  .catch(err => {
    // Block B
    res.status(400).send(err);
  });

到目前为止,即使在catch块A中出现错误,我也每次都会获得成功(200)

salalaf 回答:使用Node.js中的嵌套承诺处理错误

您可以使用Promises或async / await在一个catch块中捕获错误。您可以在每个使用promise的等待函数中专门抛出错误。  像

const a = new Promise((resolve,reject) => {
    try {
        // do something
        resolve(output);
    } catch (error) {
        reject(error);
    }
});

const b = //... similar to a();
const c = //... similar to a();

const main = async () => {
    try {
        const f = await a();
        const i = await b(f); // if data from a is to be passed to b
        const y = await c(i); // if data from a is to be passed to b
        return y;
    } catch(error){
        // catch all errors
        throw new Error( error );
    }
}

main().then(( data )=>{
    // on success do something with data

}).catch((error)=>{
    //catch all errors and do something

});

希望这会有所帮助

,

您错过了return来束缚Request.findOne()的承诺的声明。

let docs = {
  total: 0,total_downloaded: 0,plan_type: null,};

Document.findAll({
  where: {
    report_request_id: req.params.requestId
  },attributes: ["id","folder_name","total_file"],})
  .then(documents => {
    documents.forEach(document => {
        docs.total += 1;

        if (document.get("status") == 1) {
          docs.total_downloaded += 1;
        }
    });
  })
  .then(function() {
    return Request.findOne({
      where: {
        id: req.params.requestId
      }
    })
      .then(request => {
        //Suppose I got error here
        docs.plan_type = request.plan_type;
      })
      .catch(err => {
        // Block A
        throw err;
      });
  })
  .then(function() {
    res.status(200).send(docs);
  })
  .catch(err => {
    // Block B
    res.status(400).send(err);
  });

本文链接:https://www.f2er.com/3051555.html

大家都在问