What is the best approach for executing a function after completing multiple $http requests? I have come up with two solutions, but I am unsure which one is the correct one. Note that both methods log 'done' after both 'one' and 'two' requests have finished.
Firstly, I am storing all the $http requests in an array and utilizing the $q.all(promises).then
method to trigger the final callback. I cannot recall where I learned this technique, but it appears to be effective (possibly due to my fast localhost processing speed):
var one = $http.get("/request/one/"),
two = $http.get("/request/two/"),
promises;
one.then(function(response){
console.log('one');
});
two.then(function(response){
console.log('two');
});
promises = $q.all([one, two]);
promises.then(function(){
console.log('done');
});
Secondly, I have come across this method in various tutorials, such as :
var one = $q.defer(),
two = $q.defer(),
promises;
$http.get("/request/one/").then(function(response){
one.resolve('one');
});
$http.get("/request/two/").then(function(response){
two.resolve('two');
});
promises = $q.all([one.promise, two.promise]);
promises.then(function(result){
console.log('done');
});