I was going through MDN docs on Promises And came up with an example which i am not able to understand.Can Anyone explain the flow to me

Viewed 61

the promise gets resolved CB of then runs then it throws a rejected promise after that catch block runs so why the other then ran after that? i am not able to understand the flow behind it does catch also return a new promise?

code-

Promise.resolve()
  .then(() => {
    // Makes .then() return a rejected promise
    throw new Error('Oh no!');
  })
  .catch(error => {
    console.error('onRejected function called: ' + error.message);
  })
  .then(() => {
    console.log("I am always called even if the prior then's promise rejects");
  })

output- I am always called even if the prior then's promise rejects

onRejected function called: Oh no!

1 Answers

Both then() and catch() methods return a promise and the promise they return depends on two things:

  • what happens to the original promise on which they are called?

  • What is returned from their callback function?

The last then() method is called on the promise returned by the catch() method and as the catch() method, in your code, implicitly returns undefined, the promise returned by the catch() method is resolved with the value of undefined which then invokes the then() method.

If you want to stop the execution of the last then() method, then you need to reject the promise returned by the catch() method. This can be done by either rethrowing the error or returning a rejected promise.


Your code is executed as described below:

  1. Promise.resolve() returns a resolved promise

  2. Resolved promise in step 1 leads to the invocation of the Promise.resolve().then(...) method's callback function

    • As the callback function of Promise.resolve().then(...) throws an error, the promise returned by the then() method is rejected with the error object as the rejection reason.
  3. As the promise returned by the then() method in step 2 is rejected, it leads to the invocation of the catch() method's callback function.

    • Callback function of the catch() method logs the error

    • As there is no explicit return statement in the callback function of the catch() method, the callback method implicitly returns undefined.

    • The promise returned by the catch() method is resolved with the return value of its callback function, i.e. undefined

  4. As the promise returned by the catch() method is resolved, it invokes the callback function of the last then() method

Related