M
M
Mikhail R2014-11-20 18:51:40
JavaScript
Mikhail R, 2014-11-20 18:51:40

How to repeat a failed javascript promise?

I'm trying to work with promises using an example where you need to resolve 10-15 physical addresses into coordinates using the Google Maps Geocoding API, which sometimes returns an OVER_QUERY_LIMIT error , which disappears after a couple of seconds of waiting. I want to wait 1 second when receiving this error and execute the current promise again.

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() {
                    //КАК ЗАПУСТИТЬ ТЕКУЩИЙ "new Promise" ЕЩЕ РАЗ?
                }, 1000);

            } else {
                console.log(status + ': ' + results);
            }

        });
    });
});

Promise.all(proms);

In the else if , an error is caught and a timer is set for a second, what to call in this timer?
Thank you!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey, 2014-11-20
Protko @Fesor

what to call in this timer?

resolve or reject depending on the result. You can do this:
function getAddressLocation (address, repeat) {
    repeat = repeat !== false;
    
    return new Promise(function(resolve, reject) {
        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 && repeat) {
                setTimeout(function() {
                    getLocationAddress(address, false).then(resolve, reject);
                }, 1000);

            } else {
                reject(status)
            }
        });
    })
}

But it’s better to initially make some kind of queue, and not execute it immediately on demand, but in the order of the queue + it seems like you should be provided with information in the headers about the number of requests that you are allowed to make. Well, it is, to optimize all this stuff. Ida - promises can be chained, chains can be built. wedge in there, etc.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question