Retries a promise until it resolves or reaches the max attempts.
Contributed by @itsbrunodev
async function retryPromise<T>(
fn: () => Promise<T>,
maxAttempts = 3, // Retry 3 times by default
delay = 1000 // Retry after 1 second by default
): Promise<T> {
let attempts = 0;
while (attempts < maxAttempts) {
try {
return await fn();
} catch {
attempts++;
if (attempts >= maxAttempts) throw new Error("Max attempts reached.");
await new Promise((res) => setTimeout(res, delay));
}
}
throw new Error("Unexpected error.");
}
// Mock function
async function fetchData() {
if (Math.random() > 0.7) return "Success!";
throw new Error("Failed!");
}
retryPromise(fetchData).then(console.log); // Success!