Wait for all $http requests to complete in Angular JS

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 all the requests are finished. For this project I do not want to use jQuery, so please do not include jQuery in your answer. At the moment, the data is sent to the scope as each of the requests finish, which isn’t what I want to happen.

Here is part of the code I have so far.

for (var a = 0; a < subs.length; a++) {
  $http.get(url).success(function (data) {
    for (var i = 0; i < data.children.length; i++) {
      rData[data.children.name] = data.children.age;

Here is the part that I am sceptical about, because something needs to be an argument for $q.all(), but it is not mentioned on the docs for Angular and I am unsure what it is meant to be.

$q.all().then(function () {
  $scope.rData = rData;

Thanks for any help.

$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:


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

$q.all(arr).then(function (ret) {
    // ret[0] contains the response of the first call
    // ret[1] contains the second response
    // etc.

The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .
Read More:   With momentjs, how do I tell if 2 moments represent the same day (not, necessarily, the same time)?

Similar Posts