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?
2 Answers
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();
});
4 Comments
return $q.reject() is indeed a better option than throwing, but maybe you could add this option to your answer as well so that OP if sees this technique will recognize it.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.
9 Comments
$exceptionHandler in Angular, also I don't think this is what OP wants.return $q.reject();. It's much better then throwing an error. Is this also standard for Q library and not only angular's $q?throw since the $exceptionHandler hack does not exist - although you should really not be using Q in new code anymore.