javascript - 如何打破 promise 链?

标签 javascript

在这种情况下我应该如何停止 promise 链? 只有当第一个 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)
})

最佳答案

您可以在 else block 中抛出一个Error,然后在 promise 的末尾catch链:

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

关于javascript - 如何打破 promise 链?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43772154/

相关文章:

php - 使用 jQuery 自动刷新 Div 从 5 秒到零

JavaScript - 带 switch 语句的 For 循环不断循环

javascript - 如何一起使用 grunt-autoprefixer 和 grunt-sass?

javascript - 表格不同单元格上的工具提示

javascript - 流程图 : how to add a beginning and ending tick?

javascript - 更改包装的原始数据类型的值

javascript - 如何使用 javascript vuejs 有条件地导入内部 css?

javascript - 在 Javascript 中创建一个新对象

javascript - Javascript "initialize"什么时候是 RegEx 模式?

javascript - 在 Document.write() 之后调用函数时遇到问题