How to re-run a javascript promise when failed?

风格不统一 提交于 2019-12-06 15:59:37
jfriend00

You can put the main body of code into a function and call it again from the timer. Note: this is not technically rerunning a promise, it's rerunning a block of code that will then resolve the promise when 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 count so the code can never get stuck in an error loop.

You may also be interested in this post: How to avoid Google map geocode limit?.

The one time I had this error it was because I was sending requests too quickly, put a wait for a second in there between each request.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!