If you would need to fulfill the requests sequentially , you would create a promise that you could use as the head of your chain. You can then associate the $ http calls with this head and resolve the chapter promise:
aService.factory('seq', function($http, $q){ // Dummy resources. var resources = [ 'http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js', 'http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js', 'http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js' ]; var deferred = $q.defer(); var resourcePromise = deferred.promise; var res = []; angular.forEach(resources, function(resource){ return resourcePromise.then(function(){ return $http({ method: 'GET', url: resource }); }).then(function(data){ res.push({res: resource, data : data}); }); }); deferred.resolve(); return { getResource: resourcePromise.then(function(){ return res; }) }; });
but if the requests are in parallel , then this will be a simpler solution. Just an array of promises and just call the $ q.all function to wait for all promises to resolve.
aService.factory('par', function($http, $q){ // Dummy resources. var resources = [ 'http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js', 'http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js', 'http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js' ]; var promises = []; var res = []; angular.forEach(resources, function(resource){ promises.push( $http({ method: 'GET', url: resource }).then( function(data){ res.push({res: resource, data : data}); }) ); }); return { getResource: $q.all(promises).then(function(){ return res; }) }; });
Also note that in both cases we have a res array to collect query results.
EDIT: Plunker with an Example
Oleksii aza
source share