I'm trying to understand Promises from the MDN documentation. The first example demonstrates the then
and catch
methods:
// We define what to do when the promise is resolved/fulfilled with the then() call,
// and the catch() method defines what to do if the promise is rejected.
p1.then(
// Log the fulfillment value
function(val) {
log.insertAdjacentHTML('beforeend', val +
') Promise fulfilled (<small>Async code terminated</small>)<br/>');
})
.catch(
// Log the rejection reason
function(reason) {
console.log('Handle rejected promise ('+reason+') here.');
});
The documentation states that the then
method returns a new promise, so shouln't the above code be equivalent to
var p2 = p1.then(
// Log the fulfillment value
function(val) {
log.insertAdjacentHTML('beforeend', val +
') Promise fulfilled (<small>Async code terminated</small>)<br/>');
});
p2.catch(
// Log the rejection reason
function(reason) {
console.log('Handle rejected promise ('+reason+') here.');
});
?
If so, then wouldn't that mean that the catch
callback would be called only if the promise returned from p1.then
, not the promise p1
, resolved to rejected? And wouldn't I have to do this:
p1.then( /* etc. */ );
// and for rejected resolutions
p1.catch( /* etc. */ );
to catch the rejection of the promise p1
instead of chaining the catch
to the then
?
At first, I thought the promise returned from p1.then
was the same as p1
, like how jQuery does with much of its APIs. But the following clearly shows that the two promises are different.
var p1 = new Promise(function(resolve, reject) {
resolve("Success!");
});
console.log(p1);
// Promise { <state>: "fulfilled", <value>: "Success!" }
var p2 = p1.then(function(value) {
console.log(value);
});
// Success!
console.log(p2);
// Promise { <state>: "fulfilled", <value>: undefined }
Also, I played around in JSFiddle with the three approaches:
p1.then(onFulfilled).catch(onRejected);
p1.then(onFulfilled); p1.catch(onRejected);
p1.then(onFulfilled, onRejected);
All three work. I can understand the latter two. The gist of my question is, why does the first approach also work?