简体   繁体   English

带有承诺的承诺链上的“未处理的承诺拒绝”

[英]“Unhandled promise rejection” on promise chain with catch

I'm getting the exception: 我得到了例外:

(node:1356) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): Cannot edit expense on issued invoice (节点:1356)UnhandledPromiseRejectionWarning:未处理的承诺被拒绝(拒绝ID:1):无法编辑已开具发票的费用

My code uses a promise chain to update some data. 我的代码使用一个Promise链来更新一些数据。 It gets the database version first using getExpense , then checks the user is allowed to edit it (it's not been issued ). 它首先使用getExpense获取数据库版本,然后检查是否允许用户对其进行编辑(未issued )。 If it has been issued, it rejects the promise, if not it continues to perform update , then get the updated data using getExpense again in order to return it. 如果已发出,则拒绝诺言;如果否,它将继续执行update ,然后再次使用getExpense获取更新的数据以返回它。

However, when running with an 'issued' expense, the update goes through and there's the above error. 但是,以“已发出”费用运行时,更新将继续进行,并且出现上述错误。 Rejection with the message "Cannot edit expense on issued invoice" is expected, but why is it not being caught?: 预计会出现消息“无法编辑已开具发票的费用”的拒绝,但是为什么没有被捕获?:

  expensesModels.getExpense(expense.id)
    .then(validatedExpense => {
      if (validatedExpense.issued) {
        Promise.reject('Cannot edit expense on issued invoice');
      } else {
        Promise.resolve();
      }
    })
    .then(() => expensesModels.update(expense))
    .then(() => expensesModels.getExpense(expense.id))
    .then(returnExpense => response.json(returnExpense))
    .catch(err => errorHandling.onError(err, response));

I understand that this error is caused when there's not a catch terminating the promise chain, but I'm catching in order to reject the HTTP request in the last line. 我知道这个错误是在没有终止承诺链的catch时引起的,但是我捕获是为了拒绝最后一行中的HTTP请求。

您不必返回Promise.reject从你的第一个.then

To continue down the 'then' chain, 'promise.resolve()' is called on the returned value. 为了继续沿“ then”链前进,对返回值调用“ promise.resolve()”。

Since your first then function does not return the 'promise.reject()', 'promise.resolve()' is treated as the return value and the chain progresses without the error being caught. 由于您的第一个then函数不会返回'promise.reject()',因此'promise.resolve()'将被视为返回值,并且链将继续进行而不会捕获错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM