I have a code similar to this one :
promise_function().then(()=>{
//do something
return another_promise_fucntion();
}).then(() => {
//do something
return another_promise_function1();
}).then((result) => {
//check if result is valid
if(!result)
//break chain (how to stop calling the next .then functions ?)
else
return another_promise_function2();
}).then(()=>{
//do something
return another_promise_function3();
}).catch((err)=>{
//handle error
});
I want to stop calling the next .then() functions, if the returned result is not valid.
I used "throw new Error()", and it worked just fine, but I am not sure if it is the recommended way.
This rule applies when execution continues after calling the reject function in a Promise executor. The reject function of a Promise executor changes the state of the Promise , but does not stop the executor. In general, it is recommended to add a return statement after the reject to stop unintended code execution.
Promises have settled (hah) and it appears like it will never be possible to cancel a (pending) promise. Instead, there is a cross-platform (Node, Browsers etc) cancellation primitive as part of WHATWG (a standards body that also builds HTML) called AbortController .
EDIT: Also keep in mind that if you want to break out of the chain in your error handler, it needs to return a rejected promise or throw an Error (which will be caught and wrapped in a rejected promise automatically). If you don't return a promise, then wraps the return value in a resolve promise for you.
It's correct way which recommenced by Mozilla You can see more detail here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then#Chaining
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With