Elliot

Simple retry on fail pattern

Sat Feb 24

Simple retry on fail pattern

When you’re working with a system that isn’t really stable, you might want to retry the operation a few times before giving up. Sometimes, there’s nothing wrong with your function or request, but the system is just not stable. In such cases, you might want to retry the operation a few times before giving up. This is a simple pattern to do that.

This function will retry the operation a few times before giving up. It will log the error message and the number of attempts to the console.

retryOperation.js
export const retryOperation = async (
operation: () => Promise<any>,
maxAttempts: number = 3,
delayBetweenAttempts: number = 2000
) => {
let attempts = 0;
while (attempts < maxAttempts) {
try {
return await operation();
} catch (error) {
if (error instanceof Error && error.message) {
console.log( error.message);
}
attempts++;
console.log(`Retry attempt ${attempts} out of ${maxAttempts}`);
await new Promise((resolve) => setTimeout(resolve, delayBetweenAttempts));
}
}
throw new Error(`The operation failed after ${maxAttempts} attempts`);
};

You can use this function as a wrapper around your unstable or important operations.

Usage

usage.js
import { retryAsyncOperation } from "./retryAsyncOperation";
async function getSomeData() {
const operation = async () => {
// This is the operation you want to retry
return await fetch("https://unstable-api");
};
try {
const result = await retryAsyncOperation(operation);
} catch (error) {
console.error("Failed to get data:", error);
}
}