-2

Following is my code -

const fn = () => new Promise((resolve, reject) => reject());
let promise = fn();

promise
.then(() => console.log('Success 1'))
.then(() => console.log('Success 2'))
.then(() => console.log('Success 3'))
.catch(() => console.log('Error 1'))
.then(() => console.log('Success 4'))
.catch(() => console.log('Error 2'))
.then(() => console.log('Success 5'))
.catch(() => console.log('Error 3'))

Which is returning -

"Error 1"
"Success 4"
"Success 5"

My question is when a promise is settled in catch with a output Error 1 then why Success 4 and Success 5 gets logged in the console ?

Nesh
  • 2,389
  • 7
  • 33
  • 54

1 Answers1

1

One of the key things about then and catch is that they return a new promise. That new promise is settled based on A) What happens to the promise you call then or catch on, and B) What happens inside the handler function you provide (what it returns, or the error it throws).

In your code, you're catching a rejection via catch, and then you're returning undefined from it (because console.log returns undefined, and you're returning its return value) — which fulfills the promise catch created (rather than rejecting it) with the value undefined, so the fulfillment handler you hooked up with then gets called. That handler also returns undefined, fulfilling its promise, so the next then handler gets called.

In a catch handler function, if you want to reject the promise catch created, either throw an error or return a promise that is/will be rejected.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875