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
@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))