Last active
December 2, 2021 10:36
-
-
Save erikvullings/ca8694283be646688fb685036cd1eaf0 to your computer and use it in GitHub Desktop.
Asynchronous retry pattern with delay in Typescript
This file contains 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
/** 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); | |
} |
This file contains 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
/** 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