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);});
3
Answers
.catch()
returns a new pendingPromise
: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.catch
also returns a promise and since you didn’t return anything, it will be a promise that fulfills toundefined
, therefore the firstthen
printsundefined
. Finally, the lastthen
gets the value 290 from the previously returned promise by the firstthen
and prints it.When you nest multiple .then() functions in a Promise chain, each .then() function will be executed one after the other in the order they were chained.
The result of each .then() function is passed on to the next .then() function in the chain as a parameter. This allows you to perform a sequence of asynchronous operations and handle the results step-by-step.
link reference : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises#chaining