如何跳过链中的承诺

时间:2017-02-02 04:05:58

标签: javascript node.js promise

我在nodejs项目中工作,想要在链中跳过promise。以下是我的代码。在第一个promise块中,它将解析值{success: true}。在第二个块我想检查success的值,如果是,我想将值返回给被调用者并跳过此链中的其余promise;如果值为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);
});

3 个答案:

答案 0 :(得分:6)

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

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

答案 1 :(得分:2)

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

// 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);
        });
}

除此之外,还没有一种方法可以阻止中途的承诺。

答案 2 :(得分:0)

如果愿意,您还可以继续将错误沿着链条扔到最后一个捕获块。

const test = () => {
  throw new Error('boo');
}

const errorHandler = (e) => { throw e };

Promise.resolve()
        .then(console.log('then1'))
        .then(() => test())
        .then(f => console.log('then2'), errorHandler)
        .then(f => console.log('then3'), errorHandler)
        .catch((err) => console.log('caught', err));

// whoo
// then1
// caught Error: boo