Alternatively: Resolving multiple promises with $q.all()
For a custom Angular project we maintain for a client, we need to poll 2 server endpoints and collate the results.
It used to be a single server endpoint, and could potentially be 10 endpoints down the track (theoretically!)
So we use a javascript promise to make a bunch of server requests, wait for them all to succeed (or 1 to fail…) and then collate them together as the response.
Notice how this could just as easily be one request, or 10 identical requests, all returning as a nice consolidated array.
var promises = []; for(var i = 0; i < endpoints.length; i++){ var e = endpoints[i]; // load up an array of promises. promises.push(this.fetchOrdersFromEndpoint(e)); } var defer = $q.defer(); $q.all(promises).then(function(responses){ var ordersBack = [].concat.apply([], responses); // flatten multiple arrays into one defer.resolve(ordersBack); }, function(e){ defer.reject(e); }); return defer.promise;