I have a function downloadItem
that may fail for network reasons, I want to be able to retry it a few times before actually rejecting that item. The retries nee
There is no need to create new promises to handle this. Assuming downloadItem
is synchronous and returns a promise, simply return the result of calling it, along with a catch
to call downloadItemWithRetryAndTimeout
recursively.
function wait(n) { return new Promise(resolve => setTimeout(resolve, n)); }
function downloadItemWithRetryAndTimeout(url, retry) {
if (retry < 0) return Promise.reject();
return downloadItem(url) .
catch(() => wait(1000) .
then(() => downloadItemWithRetryAndTimeout(url, retry - 1)
);
}
Some might find the following slightly cleaner:
function downloadItemWithRetryAndTimeout(url, retry) {
return function download() {
return --retry < 0 ? Promise.reject() :
downloadItem(url) . catch(() => wait(1000) . then(download));
}();
}