javascript - then 回调函数中的破坏 promise 链

标签 javascript promise chaining

如何在此处停止链接中的 promise :

    .then(resp => {
      if (xxxxx) {
        return nextPromise()
      } else {
        // stop promise chain
        return
      }
    })
    .then(resp => {
       // nextPromise callback function..
    })

我以为返回会停止链条,但我错了。

最佳答案

如果您不想通过抛出错误来破坏链,解决方案是嵌套链:

.then(resp => {
  if (xxxxx) {
    return nextPromise().then(resp => {
      // nextPromise callback function..
    });
  }
})

这仍然允许全局 .catch(),您不必显式检查抛出的错误来结束链。一个缺点是,如果您有很多这样的条件,您最终会得到类似 "callback hell" 的结果。 .

关于javascript - then 回调函数中的破坏 promise 链,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43133420/

相关文章:

c# - 在 MVC.Net 中链接 lambda 表达式,而无需重复传递 HtmlHelper 对象

javascript - 按顺序执行 Ajax 请求

javascript - Angular 服务和 Controller 公共(public)范围

java - Struts2 链接到同一类的同一方法的问题

javascript - 如何在 JavaScript 中动态地从链中排除对象?

jquery - 将变量传递给 $.ajax().done()

javascript - 当底部出现下载栏时,页面上的幻灯片内容会跳起来

javascript - Javascript无法识别所有变量

javascript - 如何在 while 循环中串联连接 Promise

promise - 在 ReasonML 中从 Js.Promise 转换为 `reason-promise`