[removed] Function that retries with setTimeout

前端 未结 4 1087
灰色年华
灰色年华 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 08:01

    I've got two ideas:

    Move the promise out side of the iterated function downloadItemWithRetryAndTimeout - now resolve() will available to all iterations:

    function downloadWrapper(url, retry) {
        return new Promise(function (resolve, reject) {
            function downloadItemWithRetryAndTimeout(url, retry, failedReason) {
    
                try {
                    if (retry < 0 && failedReason != null)
                        reject(failedReason);
    
                    downloadItem(url);
                    resolve();
                } catch (e) {
                    setTimeout(function () {
                        downloadItemWithRetryAndTimeout(url, retry - 1, e);
                    }, 1000);
                }
    
            }
    
            downloadItemWithRetryAndTimeout(url, retry, null);
        });
    }
    

    This solution works, but it's an anti pattern as it breaks the promise chain: As each iteration returns a promise, just resolve the promise, and use .then to resolve the previous promise, and so on:

    function downloadItemWithRetryAndTimeout(url, retry, failedReason) {
        return new Promise(function (resolve, reject) {
            try {
                if (retry < 0 && failedReason != null)
                    reject(failedReason);
    
                downloadItem(url);
                resolve();
            } catch (e) {
                setTimeout(function () {
                    downloadItemWithRetryAndTimeout(url, retry - 1, e).then(function () {
                        resolve();
                    });
                }, 1000);
            }
        });
    }
    

提交回复
热议问题