Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Can we use multiple then in single promise returned function?

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 ?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading