Skip to content Skip to sidebar Skip to footer

Chaining Multiple Promises Created Through For Loop

I have been studying promises through this link and I understood the idea of it var parentID; $http.get('/api/user/name') .then(function(response) { parentID = response.data[

Solution 1:

You should use $q.all because it is integrated with the AngularJS digest cycle.

var parentID;

$http.get('/api/user/name')
  .then(function(response) {

      parentID = response.data['ID'];
      var promiseList = [];
      for (var i = 0; i < response.data['event-types'].length; i++) {
          var iPromise = $http.get('/api/security/' + response.data['event-types'][i]['key']);
          promiseList.push(iPromise);
      };
      return $q.all(promiseList);

  })
  .then(function(responseList) {

       console.log(responseList);

  });

From the Docs:

all(promises);

Combines multiple promises into a single promise that is resolved when all of the input promises are resolved.

Parameters

An array or hash of promises.

Returns

Returns a single promise that will be resolved with an array/hash of values, each value corresponding to the promise at the same index/key in the promises array/hash. If any of the promises is resolved with a rejection, this resulting promise will be rejected with the same rejection value.

--AngularJS $q Service API Reference -- $q.all


Solution 2:

You can utilize Promise.all(), substitute Array.prototype.map() for for loop

  var parentID;

  $http.get('/api/user/name')
  .then(function(response) {    
  parentID = response.data['ID'];
  return Promise.all(response.data['event-types'].map(function(_, i) {
    return $http.get('/api/security/' + response.data['event-types'][i]['key'])
    })) 
  })
  .then(function(response) {

    // response only returns one result of the many promises from the for loop
    // do something with parentID; 

  })
  .catch(function(err) {
    console.log(err);
  });

Post a Comment for "Chaining Multiple Promises Created Through For Loop"