Promise retry is a resilience pattern that automatically retries a failed async operation a specified number of times before giving up. This is essential for handling transient network failures, rate limits, or intermittent service unavailability.
β Implementation
function retry(fn, retries = 3, delay = 0) { return new Promise((resolve, reject) => { const attempt = (n) => { fn() .then(resolve) .catch((err) => { if (n === 0) return reject(err); setTimeout(() => attempt(n - 1), delay); }); }; attempt(retries); }); }
π§ͺ Example:
let counter = 0; const unstableTask = () => { return new Promise((res, rej) => { counter++; if (counter < 3) rej("fail " + counter); else res("success on attempt " + counter); }); }; retry(unstableTask, 5, 500) .then(console.log) .catch(console.error);
β Features:
fnis retried up toretriestimes.- Optional
delay(ms) between retries. - Stops on first success.
- Rejects with final error if all fail.
Quick Quiz
Test your understanding with 3 quick questions
Q1In the retry implementation, what happens when a retry succeeds?
Q2Why must the first argument to retry() be a function that returns a promise, rather than a promise itself?
Q3What is a common real-world use case for promise retry?