Both then()
and catch()
methods return a promise and the promise they return depends on two things:
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:
Promise.resolve()
returns a resolved promise
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.
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
As the promise returned by the catch()
method is resolved, it invokes the callback function of the last then()
method