/**
* Retries an API operation with a specified interval.
* @param {function} apiCall - The function that makes the API call. Should return a Promise.
* @param {number} maxRetries - The maximum number of retry attempts.
* @param {number} initialDelay - The initial delay in milliseconds before the first retry.
* @returns {Promise<any>} - A Promise that resolves with the result of the API call if successful, or rejects if all retries fail.
*/
async function retryApiCall(apiCall, maxRetries, initialDelay) {
let retryCount = 0;
while (retryCount < maxRetries) {
try {
const result = await apiCall();
return result; // Success!
} catch (error) {
retryCount++;
if (retryCount >= maxRetries) {
throw error; // Re-throw the error if max retries reached
}
const delay = initialDelay * Math.pow(2, retryCount); // Exponential backoff
await new Promise(resolve => setTimeout(resolve, delay));
}
}
throw new Error("Max retries reached"); // Should not reach here, but good to have a fallback
}
// Example usage (replace with your actual API call)
async function makeApiCall() {
// Simulate an API call that sometimes fails
const randomNumber = Math.random();
if (randomNumber < 0.5) {
throw new Error("API call failed!");
}
return "API response";
}
// Example: Retry the API call with 3 retries and an initial delay of 1000ms
async function runScheduledRetry() {
try {
const result = await retryApiCall(makeApiCall, 3, 1000);
console.log("API call successful:", result);
} catch (error) {
console.error("API call failed after multiple retries:", error);
}
}
Add your comment