Last active
May 15, 2024 14:54
-
-
Save pH-7/b167d6ba1cdf9f5d769da5ad094f39a2 to your computer and use it in GitHub Desktop.
Retry - A generic retry function (handy for various use cases)
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
/** | |
* A generic retry function (handy for various use cases). | |
*/ | |
const retry = async <T>(fn: () => Promise<T>, maxRetries = 3, delay = 1000): Promise<T> => { | |
let retries = 0; | |
while (retries < maxRetries) { | |
try { | |
return await fn(); | |
} catch (error) { | |
retries++; | |
if (retries === maxRetries) { | |
throw error; | |
} | |
await new Promise((resolve) => setTimeout(resolve, delay)); | |
} | |
} | |
throw new Error('Max retries exceeded'); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment