Reputation: 1975
I know how to chain promises so that multiple success functions are executed. That is esplained in many examples. How do I chain promises so that multiple error functions are executed?
Upvotes: 13
Views: 9786
Reputation: 52847
When an error is handled (and, either a value is returned or no value at all), the promise returned from then is considered resolved. You have to return a rejected promise from each error handler in order to propagate and chain error handlers.
For example:
promseA.then(
function success() {
},
function error() {
return $q.reject();
})
.promiseB.then(
function success() {
},
function error() {
return $q.reject();
})
.promiseC.then(
function success() {
},
function error() {
return $q.reject();
});
Upvotes: 33
Reputation: 105497
then
/fail
function returns a promise, which can be rejected by throwing errors. If you want to chain multiple error handlers and trigger them all you should throw error from preceding error handlers.
var d = $q.defer();
d.promise.catch(errorHandler1).catch(errorHandler2);
d.reject();
function errorHandler1 {
throw new Error();
}
function errorHandler2() {
console.log("I am triggered");
}
Or instead of catch
, you can use then
method and pass errorHandler1
and errorHandler2
as a second parameter.
Upvotes: 0