如何跳过链中的承诺

Zha*_* Yi 13 javascript node.js promise

我正在一个nodejs项目中工作,并希望在链中跳过promise.以下是我的代码.在第一个promise块中,它将解析一个值{success: true}.在第二个块我要检查值success,如果为true我想将值返回给被调用者并跳过此链中的其余promises; 如果值为false,则继续链.我知道我可以抛出错误或拒绝它在第二个块,但我必须处理错误情况,这不是一个错误的情况.那么如何在承诺链中实现这一目标呢?我需要一个解决方案而不带任何其他第三方库.

new Promise((resolve, reject)=>{
    resolve({success:true});
}).then((value)=>{
    console.log('second block:', value);
    if(value.success){
        //skip the rest of promise in this chain and return the value to caller
        return value;
    }else{
        //do something else and continue next promise
    }
}).then((value)=>{
    console.log('3rd block:', value);
});
Run Code Online (Sandbox Code Playgroud)

jib*_*jib 8

只需嵌套要跳过的链条部分(在您的情况下为其余部分):

new Promise(resolve => resolve({success:true}))
.then(value => {
    console.log('second block:', value);
    if (value.success) {
        //skip the rest of this chain and return the value to caller
        return value;
    }
    //do something else and continue
    return somethingElse().then(value => {
        console.log('3rd block:', value);
        return value;
    });
}).then(value => {
    //The caller's chain would continue here whether 3rd block is skipped or not
    console.log('final block:', value);
    return value;
});
Run Code Online (Sandbox Code Playgroud)