Created
July 25, 2020 22:43
-
-
Save karol-majewski/4f2aa94e7cf5ed6a11db8f411f1d8063 to your computer and use it in GitHub Desktop.
Retry a Promise in TypeScript
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 retry = (maxAttemps: number) => <T>(thunk: () => Promise<T>): () => Promise<T> => { | |
let attempts = 0; | |
const attempt = async (): Promise<T> => { | |
attempts++; | |
let result: T; | |
try { | |
result = await thunk(); | |
} catch(error) { | |
if (attempts === maxAttemps) { | |
throw error; | |
} | |
result = await attempt() | |
} | |
return result; | |
} | |
return attempt; | |
} |
Author
karol-majewski
commented
Jun 22, 2023
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment