How to Skip a Promise in a Chain

I work in a nodejs project and want to skip the promise in the chain. Below is my code. In the first block of the promise, it will solve the value {success: true} . In the second block, I want to check the success value, if true, I want to return the value to the called one and skip the rest of the promises in this chain; continue the chain if the value is false. I know that I can throw an error or reject it in the second block, but I need to handle the case of an error that is not an error. So how can I achieve this in the promise chain? I need a solution without any other third 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); }); 
+9
source share
3 answers

Just insert 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 chain would continue here whether 3rd block is skipped or not console.log('final block:', value); return value; }); 
+5
source

If you don't like the idea of โ€‹โ€‹nesting, you can split the rest 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); }); } 

In addition, there really is no way to stop a promise in the middle of a stream.

+2
source

You can also continue to output the error chaining to the last catch block if you wish.

 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 
0
source

Source: https://habr.com/ru/post/1014638/


All Articles