简体   繁体   English

如何跳过链中的承诺

[英]How to skip promise in a chain

I am working in a nodejs project and want to skip promise in a chain. 我正在一个nodejs项目中工作,并希望在链中跳过promise。 Below is my code. 以下是我的代码。 In the first promise block, it will resolve a value {success: true} . 在第一个promise块中,它将解析一个值{success: true} On the second block I want to check the value of success , if true I want to return the value to the called and skip the rest of the promises in this chain; 在第二个块我想检查success的值,如果是,我想将值返回到被调用者并跳过此链中的其余promises; while continue the chain if the value is false. 如果值为false,则继续链。 I know I can throw an error or reject it on the second block but I have to handle error case which it is not an error case. 我知道我可以抛出错误或拒绝它在第二个块,但我必须处理错误情况,这不是一个错误的情况。 So how can I achieve this in promise chain? 那么如何在承诺链中实现这一目标呢? I need a solution without bring any other 3rd party library. 我需要一个解决方案而不带任何其他第三方库。

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

Simply nest the part of the chain you want to skip (the remainder in your case): 只需嵌套要跳过的链条部分(在您的情况下为其余部分):

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

If you don't like the idea of nesting, you can factor the remainder of your chain into a separate function: 如果您不喜欢嵌套的想法,可以将链的其余部分分解为一个单独的函数:

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

Aside from that, there isn't really a way to stop a promise mid-stream. 除此之外,没有办法在中途停止承诺。

You could also continue to throw the error down the chain to a final catch block if you like. 如果你愿意的话,你也可以继续将链中的错误抛到最后一个catch块。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM