There are a lot of tutorials and examples of AngularJS services that make a single asynchronous request and return a single promise, but I haven’t seen many examples of complex, nested requests. With this example I will demonstrate a few complex promises in AngularJS.
I am still relatively new to AngularJS, so if you have any suggestions to improve this code please let me know.
Example 1: Multiple Parallel Async Calls
The first example is a function that makes multiple asynchronous calls and returns a list of promises that resolves after all the calls have completed. This can be useful if you need all the data from multiple sources before you can start processing it.
getAllData: function () { var promise1 = this.getData1(); var promise2 = this.getData2(); return $q.all([promise1, promise2]); }, getData1: function() { return $http.get('items1.json').then(function(res) { return res.data; }); }, getData2: function() { return $http.get('items2.json').then(function(res) { return res.data; }); }
Example 2: Multiple Nested Async Calls
The second example is a function that makes an asynchronous call and uses the results to make multiple asynchronous calls. This function returns a promise that resolves after the parent asynchronous call and all the sub-calls are completed.
getNestedData: function() { var promises = []; var deferredCombinedItems = $q.defer(); var combinedItems = []; return $http.get('itemlist.json').then(function(res) { angular.forEach(res.data, function(list) { var deferredItemList = $q.defer(); $http.get(list.name+'.json').then(function(res) { var returnedItems = res.data; combinedItems = combinedItems.concat(returnedItems); deferredItemList.resolve(); }); promises.push(deferredItemList.promise); }); $q.all(promises).then( function() { deferredCombinedItems.resolve(combinedItems); }); return deferredCombinedItems.promise; }); }
To see these AngularJS complex promises in action, check out the plunker.
About your second example, I wonder if it is equivalent to the following:
getNestedData: function() {
return $http.get(‘itemlist.json’).then(function(res) {
var promises = [];
angular.forEach(res.data, function(list) {
var deferredItemList = $q.defer();
promises.push($http.get(list.name + ‘.json’).then(function(res) {
var returnedItems = res.data;
combinedItems = combinedItems.concat(returnedItems);
}));
});
return $.all(promises);
}
}