Created
November 17, 2018 20:55
-
-
Save smddzcy/e99721ede2b2be85cfe090ed9e6e1b28 to your computer and use it in GitHub Desktop.
Retry a function a given number of times on error with a given interval.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const wait = ms => new Promise(resolve => setTimeout(resolve, ms)); | |
const retry = async (fn, retryCount = 3, intervalMs = 250, originalError) => { | |
if (retryCount === 0) { | |
if (!originalError) throw new Error('Failed after 3 retries'); | |
throw originalError; | |
} | |
try { | |
const res = fn(); | |
if (res && typeof res.catch === 'function') { | |
return res.catch(err => wait(intervalMs).then(() => retry(fn, retryCount - 1, intervalMs, err))); | |
} | |
return res; | |
} catch (err) { | |
await wait(intervalMs); | |
return retry(fn, retryCount - 1, intervalMs, err); | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment