Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stop Promise Chain execution in a recommended way [duplicate]

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.

like image 966
Abderrahman Hilali Avatar asked Apr 23 '17 12:04

Abderrahman Hilali


People also ask

Does promise resolve stop execution?

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.

Can you abort a promise?

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 .

How do you break out of a promise chain?

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.


1 Answers

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

like image 74
taile Avatar answered Sep 27 '22 20:09

taile