Reputation: 345
Usually I would do
$http({
method:'GET',
url: 'exmapleURL',
params: {someParams}
}).then(function(response) {
console.log(response); // response contains data I need
});
Now I have multiple such calls to run and I would like to wait for all of them to finish before doing something with their responses, and $q.all() seems to be a good place to start.
Per the AngularJS $q Service API Reference - $q.all document,
all(promises)
Combines multiple promises into a single promise that is resolved when all of the input promises are resolved.
Returns: Returns a single promise that will be resolved with an array/hash of values, each value corresponding to the promise at the same index/key in the promises array/hash. If any of the promises is resolved with a rejection, this resulting promise will be rejected with the same rejection value.
Does this mean that if I pass in an array of requests(like $q.all(calls).then(response)), the returned promises are in an array in the same order as the calls are passed in? Can I do something like response[0]
to retrieve the response data returned by the 0th call? Thank you.
Upvotes: 4
Views: 9983
Reputation: 48948
Does this mean that if I pass in an array of requests(like $q.all(calls).then(response)), the returned promises are in an array in the same order as the calls are passed in? Can I do something like response[0] to retrieve the response data returned by the 0th call?
Yes, the results in an array are returned in the same order:
angular.module("app",[])
.run(function($q) {
var promise99 = $q.when(99);
var promise22 = $q.when(22);
$q.all([promise22,promise99]).then(function([result22,result99]) {
console.log(result22);
console.log(result99);
});
});
<script src="//unpkg.com/angular/angular.js"></script>
<body ng-app="app"></body>
$q.all
Also Accepts Hashesangular.module("app",[])
.run(function($q) {
var promise99 = $q.when(99);
var promise22 = $q.when(22);
var promiseHash = {
r99: promise99,
r22: promise22
};
$q.all(promiseHash).then(function(resultHash) {
console.log(resultHash.r22);
console.log(resultHash.r99);
});
});
<script src="//unpkg.com/angular/angular.js"></script>
<body ng-app="app"></body>
For more information, see
Upvotes: 4