Zhao Yi Zhao Yi - 4 years ago 164
Javascript Question

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

jib jib
Answer Source

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;
});
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download