[removed] Function that retries with setTimeout

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

    @BenjaminGruenbaum comment on @user663031 is fantastic but there's a slight error because this:

    const delayError = (fn, ms) => fn().catch(e => delay(ms).then(y => Promise.reject(e)))
    

    should actually be:

    const delayError = (fn, ms) => () => fn().catch(e => delay(ms).then(y => Promise.reject(e)))
    

    so it will return a function, not a promise. It's a tricky error that's hard to solve so I'm posting on here in case anyone needs it. Here's the whole thing:

    const retry = (fn, retries = 3) => fn().catch(e => retries <= 0 ? Promise.reject(e) : retry(fn, retries - 1))
    const delay = ms => new Promise(resolve => setTimeout(resolve, ms))
    const delayError = (fn, ms) => () => fn().catch(e => delay(ms).then(y => Promise.reject(e)))
    retry(delayError(download, 1000))
    

提交回复
热议问题