AngularJS Promises, $q, defer AngularJS Promises, $q, defer angularjs angularjs

AngularJS Promises, $q, defer


IMHO I think there's a much clever (and elegant) way to do this with $q.all.

Please take a look at the code below.

I am assuming that you want to return the data at once with all the results aggregated on a big array.

var myApp = angular.module('myApp', []);myApp.factory('myService', function ($http, $q) {    return {        getAllData: function () {            return $q.all([                $http.get('../wordpress/api/core/get_category_posts/?category_id=14'),                $http.get('../wordpress/api/core/get_category_posts/?category_id=15'),                $http.get('../wordpress/api/core/get_category_posts/?category_id=16'),                $http.get('../wordpress/api/core/get_category_posts/?category_id=17')            ]).then(function (results) {                var aggregatedData = [];                angular.forEach(results, function (result) {                    aggregatedData = aggregatedData.concat(result.data);                });                return aggregatedData;            });        }    };});

You can see above that the aggregatedData is only generated once all the async calls are completed via the $q.all.

You just need to include the service as dependency into one of your controllers, for example, and call the service like this myService.getAllData()

Hope that helps or just let me know if you need a full working example and I can provide one! :)


The $http.get calls are async, but you aren't waiting until they are all completed before resolving the deferred. Here it works with the timeout simply because your are lucky that the calls have time to complete within 1 second, however this isin't reliable at all.

I will not reiterate a complete solution here, but have a look at my answer for another similar issue.