首页 文章

如何在链中跳过承诺

提问于
浏览
8

我正在一个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);
});

2 回答

  • 2

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

    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;
    });
    
  • 5

    如果您不喜欢嵌套的想法,可以将链的其余部分分解为一个单独的函数:

    // give this a more meaningful name
    function theRestOfThePromiseChain(inputValue) {
        //do something else and continue next promise
        console.log('3rd block:', value);
    
        return nextStepIntheProcess()
            .then(() => { ... });
    }
    
    function originalFunctionThatContainsThePromise() {
        return Promise.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;
                }
    
                return theRestOfThePromiseChain(value);
            });
    }
    

    除此之外,还没有办法阻止中途的承诺 .

相关问题