Collating all the http response inside a common function using $q in Angularjs

296 Views Asked by At

I am trying to use the $q service inside my controller. I have multiple environment which I need to hit and collect the data and consolidate the data and then put inside the scope. I have the below code.

     var results=[];
     for(var environment in  $rootScope.envs){
       $http.get(callService.getDomainUrl()+'/'+$rootScope.envs[environment]+ '/hosts.json').success(function(data){
              results.push(data)
          })
      }

      $q.all(results).then(function(){
          console.log(results);
      })

However, I am not sure if this is the right approach and also I need to map the result into an object of the below type:

results:{
  env1: { // result data for env1},
  env2: { // result data for env2},
  env3: { // result data for env3},
}

How to resolve the promise and consolidate the data in the above format.

2

There are 2 best solutions below

2
vp_arth On BEST ANSWER

As an addition to @SlavaUtesinov answer.
You should not to create new promises with $q.defer, just use $http.get return.

You'll get something like this:

  $q.all(Object.keys($rootScope.envs).map(request)).then(function(res){
    var results = {};
    for (var env in res) {
      results[env] = res[env].data;
    }
    console.log(results);
  }, function(err){
    console.error(err);
  });

  function request(env) {
    return $http.get(callService.getDomainUrl()+'/'+$rootScope.envs[env]+ '/hosts.json');
  }

Anyway, $q.all combine array/hash of promises into a single promise.
So, you should collect promises before call it.

7
Slava Utesinov On

You should check this example(look at log). I simulate $http.get request by means of setTimeout function.