Deka87 Deka87 - 1 year ago 49
jQuery Question

How do I know when the last asynchronous function has returned results in the "for key in ob" loop?

I have the following code to go through an obj:

var data = [];
var obj = {...
};

for (var key in obj) {
if (!obj[key]["something"]) {
geocoder.geocode({
'address': key
}, function(results, status) {
if (status === google.maps.GeocoderStatus.OK) {

data.push({...});

}
});

// if last item
$.post("...", data, ...);
}
}


Now I want to post all the data retrieved by running all asynchronous functions called in the loop.

Answer Source

Since the geocoder.geocode() (that is part of Google Maps API) doesn't return either a Promise or a Deferred, you'll have to encapsulate the request in your own Promise, then use Promise.all():

var promises = [];

for (var key in obj) {
    if (!obj[key]["something"]) {
        promises.push(new Promise(function (resolveWith, rejectWith) {
            geocoder.geocode({
                'address': key
            }, function (results, status) {
                if (status === google.maps.GeocoderStatus.OK) {
                    data.push(...);
                    resolveWith(results);
                } else
                    rejectWith(results);
            });
        }));
    }
}

Promise.all(promises).then(function (resultsArr) {
    // at this point all requests have been fulfilled
    $.post(...);
});

See MDN