Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does a `.then` callback following a `.catch` get executed?

Problem: last 2 .then are getting called even while I am returning Promise.reject(). The 1st .then() is printing undefined and 2nd .then() is also printing the output.

Can someone please explain why?

let p4 = new Promise((resolve,reject)=>{
    resolve("p4 Resolved");
});

p4.then((val)=>{
    console.log(val);
    return Promise.reject("20 Rejected")
}).catch((error)=>{console.log(error)})
  .then((val)=>{console.log(val);return 290})
  .then((val)=>{console.log("Last then : "+val);});
like image 636
Ankur Dahiya Avatar asked Oct 20 '25 12:10

Ankur Dahiya


2 Answers

catch also returns a promise and since you didn't return anything, it will be a promise that fulfills to undefined, therefore the first then prints undefined. Finally, the last then gets the value 290 from the previously returned promise by the first then and prints it.

like image 108
Victor Santizo Avatar answered Oct 23 '25 07:10

Victor Santizo


.catch() returns a new pending Promise:

Returns a new Promise. This new promise is always pending when returned, regardless of the current promise's status. It's eventually rejected if onRejected throws an error or returns a Promise which is itself rejected; otherwise, it's eventually fulfilled. — Promise#catch(), Return value | MDN

The first .then() returns a rejected promise, which as you expect, calls .catch(). However, since the callback passed to it as argument (error => { console.log(error) }) doesn't throw any errors, the new promise will be fulfilled and therefore it will call all the subsequent .then()s.

like image 32
InSync Avatar answered Oct 23 '25 08:10

InSync



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!