AngularJS Promises, $q, defer

前端 未结 2 1646
天涯浪人
天涯浪人 2020-12-02 10:43

EDIT

The first answer is the elegant one, but, as stated a few times in this question and another questions on stackoverflow, the problem is that th

相关标签:
2条回答
  • 2020-12-02 11:13

    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.

    0 讨论(0)
  • 2020-12-02 11:24

    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! :)

    0 讨论(0)
提交回复
热议问题