我如何打破承诺链? [英] How do I break a promise chain?

查看:70
本文介绍了我如何打破承诺链?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How should I stop the promise chain in this case? Execute the code of second then only when the condition in the first then is true.

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 错误 c>阻止,然后捕获它在承诺链的末尾:

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

这篇关于我如何打破承诺链?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆