Quantcast
Channel: Tech Aways » milcom
Viewing all articles
Browse latest Browse all 13

Invoking a callback after multiple async callbacks have been made in AngularJS with $q

$
0
0

While building xkcd.milcom.in, I had the need to be able to invoke multiple http calls in parallel and push the results from the those calls into an array in $scope in the order in which they were called. AngularJS provides a very elegant way to do that with the $q module. The following snippet does the trick.


//app declaration and other module definitions.

app.controller("MyController", ['$scope', '$http', '$q', function($scope, $http, $q) {</pre>
var httpCalls = [];
for(var i = 0; i < 18; i++) {
httpCalls[i] = $http.get("/get/" + i));
}

$q.all(httpCalls).then(function(results){ //$q.all ensures that 'then' is invoked after all promises from the httpCalls have been fulfilled.
for(var index in results) {
$scope.results.push(results[index].data); //the response data is encapsulated in a property called 'data'
}
 });
<pre>
}

 


Viewing all articles
Browse latest Browse all 13

Trending Articles