Angular promise on multiple $http

user1995781 picture user1995781 · Sep 26, 2015 · Viewed 9.9k times · Source

I am trying to do multiple $http call and my code looks something like this:

var data = ["data1","data2","data3"..."data10"];

for(var i=0;i<data.length;i++){
    $http.get("http://example.com/"+data[i]).success(function(data){
        console.log("success");
    }).error(function(){
        console.log("error");
    });
}

How can I have the promise to know all $http call is successfull? If anyone of it fail, will perform some action.

Answer

diegoaguilar picture diegoaguilar · Sep 26, 2015

You could also use $q.all() method.

So, from your code:

var data = ["data1","data2","data3"..."data10"];

for(var i=0;i<data.length;i++){
    $http.get("http://example.com/"+data[i]).success(function(data){
        console.log("success");
    }).error(function(){
        console.log("error");
    });
}

You could do:

var promises = [];
data.forEach(function(d) {
  promises.push($http.get('/example.com/' + d))
});
$q.all(promises).then(function(results){
  results.forEach(function(data,status,headers,config){
    console.log(data,status,headers,config);
  })
}),

This above basically means perform whole requests and set the behaviour when all have got completed.

On previous comment:

Using status you could get to know if any have gone wrong. Also you could set up a different config for each request if needed (maybe timeouts, for example).

If anyone of it fail, will perform some action.

From docs which are also based on A+ specs:

$q.all(successCallback, errorCallback, notifyCallback);