Skip to content

Instantly share code, notes, and snippets.

@erikvullings
Last active December 2, 2021 10:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save erikvullings/ca8694283be646688fb685036cd1eaf0 to your computer and use it in GitHub Desktop.
Save erikvullings/ca8694283be646688fb685036cd1eaf0 to your computer and use it in GitHub Desktop.
Asynchronous retry pattern with delay in Typescript
/** Dummy worker */
const worker = async () => {
return new Promise((resolve, reject) => {
if (Math.random() < 0.1) resolve(true);
else reject('I failed');
})
};
/** Main loop */
for (let i = 0; i<10; i++) {
const result = await retry(worker).catch(e => console.log(e));
result && console.log(result);
}
/** Wait or sleep a number of milliseconds */
const wait = (msecDuration: number): Promise<void> => {
return new Promise((resolve) => setTimeout(resolve, msecDuration));
};
/** Retry an asynchronous function a number of times, waiting in between */
export const retry = async <T>(
workerFn: { (): Promise<T>; },
retries = 3,
delay = 500
): Promise<T> => {
try {
return await workerFn();
} catch (e) {
if (retries > 1) {
await wait(delay);
return await retry(workerFn, retries - 1, delay * 2);
} else {
throw e;
}
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment