AngularJS Using $q.all to handle multiple promises


Example

You can use the $q.all function to call a .then method after an array of promises has been successfully resolved and fetch the data they resolved with.

Example:

JS:

 $scope.data = []

 $q.all([
    $http.get("data.json"),
    $http.get("more-data.json"),
    ]).then(function(responses) {
      $scope.data = responses.map((resp) => resp.data);
    });

The above code runs $http.get 2 times for data in local json files, when both get method complete they resolve their associated promises, when all the promises in the array are resolved, the .then method starts with both promises data inside the responses array argument.

The data is then mapped so it could be shown on the template, we can then show

HTML:

<ul>
   <li ng-repeat="d in data">
      <ul>
         <li ng-repeat="item in d">{{item.name}}: {{item.occupation}}</li>
      </ul>
   </li>
</ul>

JSON:

[{
  "name": "alice",
  "occupation": "manager"
}, {
  "name": "bob",
  "occupation": "developer"
}]