I\'m working on an $http call that loops over each of multiple api\'s and returns all of the data in one object. I usually have the promise ready to resolve when the $http c
If you have an arbitrary set of api calls I would do something like this:
function getSearchData(){
var deferred = $q.defer();
var noOfCalls = apiList.length;
var results = [];
var called = 0;
angular.forEach(apiList, function(item, key) {
$http.get(url).then(function(result){
results.push(result);
called++;
if(called == noOfCalls){
deferred.resolve(results);
}
})
});
return deferred.promise;
}
However if you know what each api call represents its better to use $.all in this way
function search1(){
return $http.get(search1Url).then(function(result){
// do something to it
return result;
});
}
function search2(){
return $http.get(search2Url).then(function(result){
// do something to it
return result;
});
}
function search3(){
return $http.get(search3Url).then(function(result){
// do something to it
return result;
});
}
function search4(){
return $http.get(search4Url).then(function(result){
// do something to it
return result;
});
}
function getSearchResult(){
return $q.all([search1(), search2(), search3(), search4()]).then(function(results){
// OPTIONAL aggregate results before resolving
return results;
});
}