I have an AngularJS service with such async API:
myService.asyncCall(['id0', 'id3', 'id2']).then(function (complexData) {
// handle complexData
}).catch(function (error) {
console.log(error);
});
asyncCall incapsulates multiple calls of $http which handled by $q.all. Each of the $http requests can response with error and I want the errors to be handled by one catch handler. So how i can achieve multiple calls of the catch handler ?
If I understood correctly (finally), this is what you are trying to achieve:
$q.all should be "augmented" to suit your needs, because by default:
Here is a possible implementation:
function asyncCall(listOfPromises, onErrorCallback, finalCallback) {
listOfPromises = listOfPromises || [];
onErrorCallback = onErrorCallback || angular.noop;
finalCallback = finalCallback || angular.noop;
// Create a new list of promises that can "recover" from rejection
var newListOfPromises = listOfPromises.map(function (promise) {
return promise.catch(function (reason) {
// First call the `onErrroCallback`
onErrorCallback(reason);
// Change the returned value to indicate that it was rejected
// Based on the type of `reason` you might need to change this
// (e.g. if `reason` is an object, add a `rejected` property)
return 'rejected:' + reason;
});
});
// Finally, we create a "collective" promise that calls `finalCallback` when resolved.
// Thanks to our modifications, it will never get rejected !
$q.all(newListOfPromises).then(finalCallback);
}
See, also, this short demo.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With