[removed] Function that retries with setTimeout

前端 未结 4 1097
灰色年华
灰色年华 2021-01-03 07:16

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

4条回答
  •  太阳男子
    2021-01-03 07:57

    function downloadItemWithRetryAndTimeout(url, retry) {
        return new Promise(function(resolve, reject) {
            var tryDownload = function(attempts) {
                try {
                    downloadItem(url);
                    resolve();
                } catch (e) {
                    if (attempts == 0)  {
                        reject(e);
                    } else {
                        setTimeout(function() {
                            tryDownload(attempts - 1);
                        }, 1000);
                    }
                }
            };
            tryDownload(retry);
        });
    }
    

提交回复
热议问题