[removed] Function that retries with setTimeout

前端 未结 4 1065
灰色年华
灰色年华 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:47

    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));
      }();
    }
    

提交回复
热议问题