返回承诺并捕获错误

Returning a promise and catching an error

我对何时将 promise 中的错误传递给 catch 处理程序感到有点困惑。

使用下面的代码,如果 promise2 导致错误,是否传递给底部的 catch?此外,我的 return 是在第一个 "then" return promise2 中作为承诺,还是 return doc.

promise1(foo).then(doc =>{
  return promise2(doc).then(doc => {
    return doc
  })
}).then(doc =>{
  console.log(doc)
}).catch(err => {
  console.error(err)
})

干杯

一个 then 可以 return 一个承诺,但是如果某件事失败了,你需要明确地 return 一个拒绝。在下面的示例中,changedDoc 作为 newDoc

传递给第二个 then
promise1(foo).then(doc =>{
  // changedDoc = doc.....
  if (good things happened) {
     return changedDoc;
  } else {
     return new Promise.reject("error");
  }
}).then(newdoc =>{
  console.log(newdoc)
}).catch(err => {
  console.error(err)
})

then可以接收两个参数:

  • 一个是兑现承诺的情况
  • 其他情况下承诺被拒绝(有意或因为抛出异常)

如果代码执行出错,无论是fullfilled,还是rejected,都会在下一个rejected回调中继续执行。在您的代码中,第一个被拒绝的回调是 catch 回调中指定的回调。如果该块不存在,异常将一直冒泡到代码中的第一个 catch 块。而且,如果没有这样的块,它将由浏览器处理,并向用户显示为错误。

如果你 look at the documentation,你会发现 catch 就像一个只接收第二个参数的 then

Promise.prototype.then(onFulfilled, onRejected)

Promise.prototype.catch(onRejected)

你也可以看看this documentation on handling exceptions with promises

promises 的整个想法就是能够链接,这样成功就会传播到 onFullfilled 回调,它可以 运行 没有错误,并且 return 一些东西下一个 onFullfilled 处理程序,或有错误的 运行,将由下一个 onRejected 处理。错误可以是有目的的拒绝,也可以是未处理的异常。