How to restart javascript promise on unsuccessful attempt?

I have the following code where I am trying to convert a list of 10-15 addresses in a businesses array to lat / lng coordinates using the Google Maps geocoding API.

 var geocoder = new google.maps.Geocoder(); var proms = businesses.map(function(address) { return prom = new Promise(function(resolve) { geocoder.geocode({ address: address }, function(results, status) { if (status === google.maps.GeocoderStatus.OK) { resolve({ results: results, business: address }); } else if (status === google.maps.GeocoderStatus.OVER_QUERY_LIMIT) { setTimeout(function() { //HOW DO I RE-RUN THIS "new Promise"? }, 1000); } else { console.log(status + ': ' + results); } }); }); }); Promise.all(proms); 

The problem is that the Google API sometimes returns an OVER_QUERY_LIMIT error, so I was wondering if there was a way to re-execute a promise that didn’t pass after a few seconds. In the above example, the else if catches the error, so how can I do it again after a timeout?

Please note that I just started using promises and have not yet figured out how they work, so my approach may be completely wrong. Also, all this is done under the assumption that the Google API will not allow me to resolve addresses in bulk, if this is not so, please let me know.

+1
javascript promise google-geocoding-api
source share
2 answers

You can put the main code in the function and call it again from the timer. Note: this does not technically repeat the promise, it restarts a block of code that will then resolve the promise when it is done:

 var proms = businesses.map(function(address) { return prom = new Promise(function(resolve, reject) { var retriesRemaining = 5; function run() { geocoder.geocode({ address: address }, function(results, status) { if (status === google.maps.GeocoderStatus.OK) { resolve({ results: results, business: address }); } else if (status === google.maps.GeocoderStatus.OVER_QUERY_LIMIT) { --retriesRemaining; if (retriesRemaining <= 0) { reject(status); } else { setTimeout(run, 1000); } } else { console.log(status + ': ' + results); } } }); } run(); }); }); Promise.all(proms); 

FYI, I also added a retry counter, so the code can never get stuck in the error loop.

You may also be interested in this post: How to avoid limiting the geocode of a Google map? .

+2
source share

Once I had this error, because I sent requests too quickly, set expectations between them for a second.

-one
source share

All Articles