I am reading a book named You dont know JS. I am at the part where the author is explaining why errors in the promise.then()
's success callback isn't designed to be caught in the error callback in the same promise.then()
. In other words:
somePromise.then(
function success(msg){
throw new Error()//Line A
},
function error(err){
//error at Line A will not be caught here
}
);
Here is the actual content from the book:
var p = new Promise( function(resolve,reject){
resolve( 42 );
} );
p.then(
function fulfilled(msg){
foo.bar(); //Line C: will throw error because foo is null
console.log( msg ); // never gets here :(
},
function rejected(err){//Line D
// never gets here either :(
}
);
Why couldn't it just call the error handler we have defined there (he is talking about callback at Line D)? Seems like a logical behavior on the surface. But it would violate the fundamental principle that Promises are immutable once resolved. p was already fulfilled to the value 42, so it can't later be changed to a rejection just because there's an error in observing p's resolution.
I have problem with this line:
p was already fulfilled to the value 42, so it can't later be changed to a rejection just because there's an error in observing p's resolution.
IMO, even if the error in Line C would have been designed to be caught in Line D, it wouldn't have any impact on original promise (p
). Simply because .then()
will return a new promise which is in no way related to original promise. Author seems to think otherwise. IMHO, what they should have said instead:
When an error is thrown in Line C, a new, rejected Promise
has been created so it can't later be given to callback at Line D, since rejected Promise
is immutable Promise
.
Am I missing something here?
Source of content: link