Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to skip promise in a chain

I am working in a nodejs project and want to skip promise in a chain. Below is my code. In the first promise block, it will resolve a value {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; while continue the chain if the value is 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);
});
like image 525
Joey Yi Zhao Avatar asked Feb 02 '17 04:02

Joey Yi Zhao


2 Answers

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;
});
like image 52
jib Avatar answered Sep 19 '22 00:09

jib


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.

like image 44
JLRishe Avatar answered Sep 20 '22 00:09

JLRishe