About the promise chain in ES6

I got confused about the Promise chain in ES6.

function taskA() { console.log("Task A"); throw new Error("throw Error @ Task A") } function taskB() { console.log("Task B"); } function onRejected(error) {  console.log(error);// => "throw Error @ Task A" } function finalTask() { console.log("Final Task"); } var promise = Promise.resolve(); promise .then(taskA) .then(taskB) .catch(onRejected) .then(finalTask); 

What have I lost here, why will finalTask be called? Does the catch() chain return an allowed promise?

+5
source share
1 answer

When you provide a .catch() handler or second argument to .then() , the rejected promise is “processed”. By default, when you provide such a rejection handler, the promise system will assume that the rejection has been processed and the chain should continue.

If you do not want the chain to continue, then from the rejection handler, you can either return the rejected promise or throw an error. This will stop this chain until another handler appears in the chain.

So, here are the possibilities in the chain, as you show:

1) There is no deviation handler in the chain

The chain is completely stopped and executable .then() handlers are not executed.

2) There is a rejection handler in the chain that either does not return anything or returns a regular value or a fulfilled promise or a promise that ultimately fulfills.

Here is what your code shows. The deviation is considered processed, and the promised state of the chain changes to the fulfilled promise, therefore, subsequent execution handlers in the chain are called.

3) There is a rejection handler in the chain that either returns a rejected promise or gives an error

Returning a rejected promise (or a promise that is rejected in the future) or throwing a new error (which turns into a rejected promise) will stop further processing of the chain until the next error handler.

So, if you changed the onRejected() handler to this:

 function onRejected(error) {  console.log(error); throw error; // rethrow error to stop the rest of the chain } 

Then your promise chain will stop there.


It is important to understand why it works this way. This allows you to handle the error in the middle of the promise chain, and the error handling code allows you to decide whether the chain continues or not, based on whether it returns or throws. If it does not return anything or a normal value or a fulfilled promise, the processing of the chain continues - the error has been processed - there is no need to stop further processing.

But if the error is more serious, and the processing should not continue, then the rejection handler can either throw the same error, throw a different error, or return a rejected promise, and the chain will skip any execution handlers until the next rejection handler in the chain.

+13
source

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


All Articles