Skip to content

Instantly share code, notes, and snippets.

@radzserg
Created January 10, 2022 17:09
Show Gist options
  • Save radzserg/8852e2321023f7d7856f93395161d66e to your computer and use it in GitHub Desktop.
Save radzserg/8852e2321023f7d7856f93395161d66e to your computer and use it in GitHub Desktop.
const withRetry = (
func: (...args: any[]) => Promise<any>,
maxAttempts: number = 3,
timeout: number = 1_000
) => {
const sleep = (ms: number) => {
return new Promise((resolve) => {
return setTimeout(resolve, ms);
});
};
const withRetryCapability = async (
attempt: number,
...args: any
): Promise<any> => {
try {
return await func(...args);
} catch (error) {
if (error.code && error.code === 'rate_limit' && attempt <= maxAttempts) {
await sleep(timeout * attempt);
return await withRetryCapability(attempt + 1, ...args);
}
throw error;
}
};
return (...args: any) => {
return withRetryCapability(1, ...args);
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment