Last active
November 15, 2024 13:42
-
-
Save Yuripetusko/cb7d7f176115e09738c7f728aa25191d to your computer and use it in GitHub Desktop.
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
| export function retryWithExponentialBackoff<T extends () => Promise<Awaited<ReturnType<T>>>>( | |
| fn: T, | |
| maxAttempts = 5, | |
| baseDelayMs = 1000, | |
| ) { | |
| let attempt = 1; | |
| const execute = async () => { | |
| try { | |
| return await fn(); | |
| } catch (error) { | |
| if (attempt >= maxAttempts) { | |
| throw error; | |
| } | |
| const delayMs = baseDelayMs * 2 ** attempt; | |
| console.log(`Retry attempt ${attempt} after ${delayMs}ms`); | |
| await new Promise((resolve) => setTimeout(resolve, delayMs)); | |
| attempt++; | |
| return execute(); | |
| } | |
| }; | |
| return execute(); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment