You should just forget that .then()
even takes more than 1 argument and use the .catch
method and it will make more sense.
Promises provide a correspondence to some sync code constructs but this isn't very visible when you just have a low-level .then()
. What you are looking for is basically an array of callbacks/callback aggregation but that is not the point of promises at all.
Think of .catch(fn)
same as .then(null, fn)
:
doSomething().then(function(val) {
console.log(val);
}).catch(function(e) {
console.error(e);
});
Parallels the sync code (imagine doSomething
returns synchronously):
try {
var val = doSomething();
console.log(val);
}
catch(e) {
console.error(e);
}
Multiple catches (remember that .catch
is more readable alias to .then(null, fn)
doSomething().then(function(val) {
console.log(val);
}).catch(function(e) {
return e;
}).catch(function(e){
//Will not get here ever
//because error thrown from doSomething()
//was handled in the upper catch which doesn't trow
});
Parallels:
try {
try {
var val = doSomething();
console.log(val);
}
catch(e) {
//no need for explicit return e
}
}
catch( e ) {
//Will not get here ever
//because error thrown from doSomething()
//was handled in the upper catch which doesn't trow
}
So now you should notice that you can create the expected result by throwing instead of returning http://jsfiddle.net/VYSj7/3/
.catch()
is IMO an essential method for a promise library to provide and will also be included in the built-in Javascript promises in future. However,
if such method isn't provided, you can (or should be, unfortunately there are implementations that don't use prototypes):
Promise.prototype.catch = function(fn) {
return this.then(null, fn);
};
See also rejection turns into fulfillment