Skip to content

Instantly share code, notes, and snippets.

@crypt0miester
Last active December 23, 2024 10:43
Show Gist options
  • Save crypt0miester/8bf545536011a89daf16d73720aa1de3 to your computer and use it in GitHub Desktop.
Save crypt0miester/8bf545536011a89daf16d73720aa1de3 to your computer and use it in GitHub Desktop.
export type RetryConfig = {
maxAttempts?: number;
initialDelay?: number;
maxDelay?: number;
backoffFactor?: number;
onRetry?: (error: Error, attempt: number) => void;
};
export async function retryOnFailure<T>(
operation: () => Promise<T>,
config: RetryConfig = {},
): Promise<T> {
const {
maxAttempts = 3,
initialDelay = 1000,
maxDelay = 5000,
backoffFactor = 2,
onRetry = () => {},
} = config;
let lastError: Error;
let delay = initialDelay;
for (let attempt = 1; attempt <= maxAttempts; attempt++) {
try {
return await operation();
} catch (error) {
lastError = error as Error;
if (attempt === maxAttempts) {
throw lastError;
}
// call the onRetry callback
onRetry(lastError, attempt);
// sleep before retrying
await new Promise((resolve) => setTimeout(resolve, delay));
// calculate next delay with exponential backoff
delay = Math.min(delay * backoffFactor, maxDelay);
}
}
throw lastError!;
}
@crypt0miester
Copy link
Author

how to use:

    const response = await retryOnFailure(
      async () => {
        return await asyncFunction()
      },
      {
        maxAttempts: 3,
        initialDelay: 500,
        onRetry: (error, attempt) => {
          console.warn(
            `Retry attempt ${attempt} for getOnDemandIxn failed:`,
            error.message,
          );
        },
      },
    );
    ```

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment