Chaining promises from a foreach loop
Promises are chained by returning values (or a promise) to the handler function in the .then
method. Multiple promises are consolidated by using $q.all
which itself returns a chainable promise.
function fetchUsers(arg) {
var articles = arg;
var promises = articles.map(function(a){
var subPromises = [fetchImg(a), fetchUser(a)];
return $q.all(subPromises).then(function (res) {
//return for chaining
return {img: res[0], user: res[1]};
});
});
//consolidate promises
var finalPromise = $q.all(promises);
return finalPromise;
};
Because calling the .then
method of a promise returns a new derived promise, it is easily possible to create a chain of promises. It is possible to create chains of any length and since a promise can be resolved with another promise (which will defer its resolution further), it is possible to pause/defer resolution of the promises at any point in the chain.1
The returned promise will either resolve fulfilled with an array of users or will resolve rejected with the first error. Final resolution is retrieved with the promise's .then
and .catch
methods.
fetchUsers(args)
.then ( function onFulfilled(objArray) {
$scope.users = objArray.map(x => x.user);
return objArray;
}).catch ( function onRejected(response) {
console.log("ERROR: ", response);
throw response
})
;
The $q.defer
Anti-pattern
The problem with using $q.defer()
is that it breaks the promise chain, loses error information, and can create memory leaks when errors are not handled properly. For more information on that see, AngularJS Is this a “Deferred Antipattern”?.