A retry mechanism automatically retries a failed API call a certain number of times, often with a delay, to handle temporary network issues or server errors.
1️⃣ Basic Retry Function
async function fetchWithRetry(url, options = {}, retries = 3, delay = 1000) {
for (let i = 0; i <= retries; i++) {
try {
const response = await fetch(url, options);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return await response.json(); // success
} catch (err) {
if (i < retries) {
console.log(`Retrying... attempt ${i + 1}`);
await new Promise(res => setTimeout(res, delay)); // wait before retry
} else {
throw err; // all retries failed
}
}
}
}
2️⃣ Usage Example
fetchWithRetry("https://api.example.com/data", {}, 3, 1000)
.then(data => console.log("Data:", data))
.catch(err => console.error("Failed after 3 retries:", err));
✅ What happens:
- Try API call
- If it fails → wait 1s → retry
- Repeat up to 3 times
- If all fail → throw error
3️⃣ Optional Enhancements
- Exponential Backoff: Increase delay after each retry
await new Promise(res => setTimeout(res, delay * Math.pow(2, i)));
- Retry Only on Certain Errors:
if (response.status >= 500) { /* retry */ }
- Abort on Certain Errors: Stop retrying if client error (400–499)
⚡ In short:
A retry mechanism attempts an API call multiple times with optional delay, handling temporary failures gracefully. Using
async/awaitwith aforloop andsetTimeoutis the simplest and cleanest approach.