zilcuanu
zilcuanu

Reputation: 3715

mapping the response to corresponding request

I am making $http request to multiple environment and processing after I get all the responses. I am using the code below:

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

}, function(err){
  console.error(err);
});

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

The above code works fine, but the results object looks like below:

{
  0: {data:{}}, 
  1: {data:{}}, 
  2: {data:{}}, 
  3: {data:{}}
}

I want the corresponding response for each key and the results should be like

{
  env1: {data:{//data for env1}}, 
  env2: {data:{//data for env2}}, 
  env3: {data:{//data for env3}}, 
  env4: {data:{//data for env4}}, 
}

How to map the corresponding response to the key? Please let me know how to get this as this is asynchronous request. Should I have something from the API to know which env the API is coming from?

Upvotes: 1

Views: 943

Answers (1)

Duncan
Duncan

Reputation: 95732

I think the simplest way would be to push the result handling into the request function, that way you still have the 'env' value in scope.

var results = {};

$q.all(Object.keys($rootScope.envs).map(request)).then(function(res){
   // Do something with 'results' here.
}, function(err){
  console.error(err);
});

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

Another option would be to replace my return env with return [env, res.data] and then you can go back to creating the results object as in your original code.

The important thing here is to remember you can handle the $http.get promises individually as well as using the promises from the call to then in $q.all.

Upvotes: 0

Related Questions