I am having a synchronization issue with third party API.
My “for loop” seem to be running quickly, throwing off API requests
which may return data in any order.
How can I restructure this to endure that DoSomething is run synchronously?
function startgeocoding() {
for(var x = 0; x < address2.length; x++ ) {
geocode(address);
}
}
function geocode(address) {
if (geocoder) {
geocoder.geocode({ 'address': address }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
DoSomething();
}
}
}
You could call
geocode()on the next element in the success callback to create a chain of calls. The calls would still be asynchronous but you aren’t geocoding the next one until the first one finishes. Something like:Another option might be to leave it the way you have it, but queue up the results, sort them somehow, and then do work on them once all of the synchronous calls have completed in the order you wish.