0

Using AngularJs 1.6.5 I am making multiple $http GET calls using the for loop. Here is the code:-

for(var i=0; i < 11; i++){  
    var url = "/api/learner_qa/" + i;   
    $http.get(url).then(successCallback, errorCallback);    
    function successCallback(response){
        console.log(response);
    };
    function errorCallback(error){
        console.log(error);
    };
};

What I want to do is trigger a function when all the GET requests are completed.

I referred to answer posted here and want to know how can this be done on an array as in my case?

Shashishekhar Hasabnis
  • 1,636
  • 1
  • 15
  • 36
  • you can just increment a counter into the successCallback and when this counter is == 11 dispatch the new function. – justcode May 30 '18 at 11:39

1 Answers1

6

The time will likely arise where you need to resolve multiple promises at once, this is easily achieved through $q.all() by passing in either an Array or Object of promises which will call .then() once both are resolved:

You can take an array and push your http calls into it

var array  = [];
for(var i=0; i < 11; i++){  
    var url = "/api/learner_qa/" + i;   
    array.push($http.get(url))
};

$q.all(array).then(function(response) {
     console.log(response)
}).catch(function(error){
    console.log(error)
});

Using this code, the response will come once all your requests are successful.

Here is an example documentation

Sravan
  • 18,467
  • 3
  • 30
  • 54