I am new to Promises, and am running into unexpected behaviour when experimenting with the .then method. The promise below is rejected, and a value is returned by the function within the .then method, yet the promise shows {: ‘Error goes here’}.
var myPromise = new Promise((res,rej)=>{
rej("Error goes here")
})
.then(function(a){},
function(error) {
return error;
})
//Returns "{<fulfilled>: 'Error goes here'}"
Why is this showing as ‘fulfilled’.
2
Answers
The second argument of the
.then()
method is the same as a.catch()
handler.In your code, the rejection will trigger that catch handler, which will return the value of the error. Because the error is considered handled, the final promise will be fullfilled with the same string that used to be the rejection reason.
Note that a
.catch()
behaves the same way:To forward the rejection from a catch handler, you have to re-throw the error:
This behavior is very similar to how a normal
try..catch
behaves:.then()
method accepts two parameters: a callback for fulfilled and callback for rejected. You’re returning the error from the second callback (the one for rejected promises) but, it doesn’t actually cause the promise to be fulfilled. Instead, it returns a new promise that is fulfilled with the value returned by the second callback. Then, that value is the error message, so the new promise is fulfilled with that error message.