javascript - 在 Node js 中处理嵌套 promise 的错误

标签 javascript node.js sequelize.js es6-promise

当嵌套的 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)

最佳答案

您错过了链接 return promise 的 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);
  });

关于javascript - 在 Node js 中处理嵌套 promise 的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58992616/

相关文章:

javascript - 针对未经验证的代码保护 SSJS

node.js - lambda 边缘 "The Lambda function returned invalid json: The json output is not parsable."

ajax - AJAX 和 Node.js 交互的问题

javascript - 为什么我的后端不更新数据库中的关键字数据列

sequelize.js - 通过 Sequelize 在 MySQL 中将 1|2|3 存储为整数

node.js - 调用 activator.init 后,Sequelize 急切加载会引发错误

javascript - 带有 http-mock 和伪装者的 Ember CLI,如何管理模拟数据

javascript - 在 X 个结果后包装数据的 CSS 元素

javascript - errmsg : 'Unsupported projection option: $push: { ... }' , 代码 : 2, codeName: 'BadValue' }

javascript - 如果选择另一个字段,则更新表中的字段