Reputation: 105
Just a quick clarification question:
is there any difference between
promiseGeneratingFunction.then(successHandler, errorHandler).done();
and
promiseGeneratingFunction.then(successHandler).catch(errorHandler).done();
?
Thanks
Upvotes: 0
Views: 159
Reputation: 161457
The other answers are not considering the effects of chaining. The docs say:
A sugar method, equivalent to promise.then(undefined, onRejected).
So yes, .catch
is equivalent to .then
. But that isn't what your examples show.
You compare
promiseGeneratingFunction.then(successHandler, errorHandler).done();
// VS
promiseGeneratingFunction.then(successHandler).catch(errorHandler).done();
If we break the second example down using the documented comparison, it is actually:
promiseGeneratingFunction.then(successHandler, errorHandler).done();
// VS
promiseGeneratingFunction.then(successHandler).then(undefined, errorHandler).done();
Those two behave differently in how they handle errors. Both examples will call successHandler
if the generated promise succeeds, and call errorHandler
if the promise fails, so they are very similar. The difference comes from how they handle errors in successHandler
.
// this is a fulfilled promise since the thrown error was handled
Promise.resolve().then(function(){ throw new Error(); }).catch(function(){});
// this is a rejected promise
Promise.resolve().then(function() { throw new Error() }, function(){});
If your successHandler
function were to throw an exception (or return a rejected promise), your first example has no error handler attached (errorHandler
is only attached to promiseGeneratingFunction
, so your promise will throw an uncaught exception from the .done()
. On the second example, the error thrown from successHandler
would also be caught in errorHandler
since it is bound farther down the promise chain.
The equivalent synchronous code is something like this:
var error = null;
var result;
try {
result = func();
} catch (err){
error = err;
}
if (error){
errorHandler(error);
} else {
successHandler(result);
}
// VS
try {
var result = func();
successHandler(result);
} catch (err){
errorHandler(err);
}
Upvotes: 7
Reputation: 4859
Q promises provide a fail shorthand for then when you are only interested in handling the error
As said documentation, it's only shorthand
Upvotes: -2