Skip to content

Instantly share code, notes, and snippets.

@pH-7
Last active May 15, 2024 14:54
Show Gist options
  • Save pH-7/b167d6ba1cdf9f5d769da5ad094f39a2 to your computer and use it in GitHub Desktop.
Save pH-7/b167d6ba1cdf9f5d769da5ad094f39a2 to your computer and use it in GitHub Desktop.
Retry - A generic retry function (handy for various use cases)
/**
* 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