Skip to content

Instantly share code, notes, and snippets.

@smddzcy
Created November 17, 2018 20:55
Show Gist options
  • Save smddzcy/e99721ede2b2be85cfe090ed9e6e1b28 to your computer and use it in GitHub Desktop.
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.
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