如何打破承诺链?

新手上路,请多包涵

在这种情况下我应该如何停止承诺链?只有当第一个 then 中的条件为真时,才执行第二个 then 的代码。

 var p = new Promise((resolve, reject) => {
    setTimeout(function() {
        resolve(1)
    }, 0);
});

p
.then((res) => {
    if(true) {
        return res + 2
    } else {
        // do something and break the chain here ???
    }
})
.then((res) => {
    // executed only when the condition is true
    console.log(res)
})

原文由 vincentf 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 303
2 个回答

You can throw an Error in the else block, then catch it at the end of the promise chain:

 var p = new Promise((resolve, reject) => {
    setTimeout(function() {
        resolve(1)
    }, 0);
});

p
.then((res) => {
    if(false) {
        return res + 2
    } else {
        // do something and break the chain here ???
      throw new Error('error');
    }
})
.then((res) => {
    // executed only when the condition is true
    console.log(res)
})
.catch(error => {
  console.log(error.message);
})

演示 - https://jsbin.com/ludoxifobe/edit?js,console

原文由 Nick Salloum 发布,翻译遵循 CC BY-SA 3.0 许可协议

您可以阅读 文档,其中说

Promise.then 如果输入函数抛出错误,或者输入函数返回一个被拒绝的Promise,则返回一个被拒绝的Promise。

如果您愿意,可以阅读关于 then 的部分中的 Promise A 规范,其中 promise2 指的是最终的承诺:

If either onFulfilled or onRejected throws an exception e , promise2 must be rejected with e as the reason.)

如果您愿意,可以阅读出色的 2ality 博客

then() 返回一个新的承诺 Q(通过接收者的构造函数创建): 如果任一反应返回一个值,Q 将被解决。 如果任一反应抛出异常,Q 将被拒绝。

你可以阅读精彩的 YDKJS

在 then(..) 调用的实现或拒绝处理程序中抛出的异常会导致下一个(链接的)承诺立即被该异常拒绝。

原文由 user663031 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题