Wait for all $http requests to complete in Angular JS

后端 未结 1 812
独厮守ぢ
独厮守ぢ 2020-12-08 00:52

I have a page than can make a different number of $http requests depending on the length of a variables, and then I want to send the data to the scope only when

相关标签:
1条回答
  • 2020-12-08 01:37

    $http call always returns a promise which can be used with $q.all function.

    var one = $http.get(...);
    var two = $http.get(...);
    
    $q.all([one, two]).then(...);
    

    You can find more details about this behaviour in the documentation:

    all(promises)

    promises - An array or hash of promises.

    In your case you need to create an array and push all the calls into it in the loop. This way, you can use $q.all(…) on your array the same way as in the example above:

    var arr = [];
    
    for (var a = 0; a < subs.length; ++a) {
        arr.push($http.get(url));
    }
    
    $q.all(arr).then(function (ret) {
        // ret[0] contains the response of the first call
        // ret[1] contains the second response
        // etc.
    });
    
    0 讨论(0)
提交回复
热议问题