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()

Let me know if you need a full working example and I can provide one! 🙂

Leave a Comment