How To Execute Only After All Ajaxcalls Are Made?
Solution 1:
You could use a counter initialized to 0. Increment it each time a get/post is finished. Call the function you want to execute only if the counter gets to the number of get/posts you want.
Solution 2:
at the time of execution, there is only one promise to resolve - httpData1
you have to call $q.all
after httpData2
is set
the problem is that you may have more than one additional promise to resolve, so you should collect them and return as a bulk promise:
adminApp.controller('PollController', function($scope,$window,$timeout, $rootScope,$routeParams, $http, $location, $q) {
displayLoader("Loading...", "100px");
$http({
method: 'get',
url: "the url",
}).then(function(response) {
$scope.poll = response;
var promises = [];
for (var i = 0; i < response.length; i++) {
promises.push(getPollById(response[i], i));
angular.element('#loadering').fadeOut('slow');
}
return$q.all(promises);
}, function(response) {
console.log(response || "Request failed");
}).then(function() {
console.log("all calls have finished ");
})
functiongetPollById(i, index)
{
return$http({
method: 'post',
url: BASE_URL+'admin_api/admin_poll_api/admin_poll/',
data: i
}).then(function(response) {
appendData(response, index);
var labels = [];
var data = [];
for (var i = 0; i < response.response.options.length; i++) {
labels.push(response.response.options[i].options);
data.push(response.response.options[i].votes);
}
}, function(response) {
console.log(response || "Request failed");
});
}
$scope.polls=[];
functionappendData(response, index){
$scope.polls[index] = response;
}
});
what I have done here is to chain your main promise with bulk of additional promises
Solution 3:
keep in mind that $q.all will exit after first reject, if you want to be sure that all promises ended (resolved or rejected), you may use angular promise extras module (https://github.com/ohjames/angular-promise-extras) whith its $q.allSettled method. So you can just replace $q.all() in pwolaq's nice answer with:
$q.allSettled (promises);
Post a Comment for "How To Execute Only After All Ajaxcalls Are Made?"