Anirban Anirban - 1 month ago 10
Ajax Question

Wait for AngularJs Ajax Calls to complete

I have the following Ajax call:

for (var i=0;i<localStorage.length;i++){
stored = localStorage.getItem(i.toString());
id=stored.split(':');
if ( id[0].toString()=="legislator" ){
bioguide_id=id[1];
$http({
method: 'GET',
url: 'getData.php',
params: {fav_legislator_value: bioguide_id}
}).then(function (response) {
fav_legislators.push(response.data.results[0]);})
}
}


I need all the Ajax call to complete and all results pushed to the array after that only I can start processing again. I have tried many ways by making this a function but nothing works. My whole script gets executed then the values are pushed to the array which is of no use to me. How to wait until all the calls are completed and the array is completely populated.

Answer

Store all the promises object into an array, and use $q.all to combine all promises into a single promise which will be resolved only if all of them have been resolved.

E.g.

var promises = [];

for (var i=0;i<localStorage.length;i++){
    stored = localStorage.getItem(i.toString());
    id=stored.split(':');
    if ( id[0].toString()=="legislator" ){
        bioguide_id=id[1];
        var req = $http({
            method: 'GET',
            url: 'getData.php',
            params: {fav_legislator_value: bioguide_id}
        }).then(function (response) {
            fav_legislators.push(response.data.results[0]);
        });

        promises.push(req);
    }
}

$q.all(promises).then(function () {
    // All result is now in `fav_legislators`.
})
Comments