1. /**
  2. * Retries an API operation with a specified interval.
  3. * @param {function} apiCall - The function that makes the API call. Should return a Promise.
  4. * @param {number} maxRetries - The maximum number of retry attempts.
  5. * @param {number} initialDelay - The initial delay in milliseconds before the first retry.
  6. * @returns {Promise<any>} - A Promise that resolves with the result of the API call if successful, or rejects if all retries fail.
  7. */
  8. async function retryApiCall(apiCall, maxRetries, initialDelay) {
  9. let retryCount = 0;
  10. while (retryCount < maxRetries) {
  11. try {
  12. const result = await apiCall();
  13. return result; // Success!
  14. } catch (error) {
  15. retryCount++;
  16. if (retryCount >= maxRetries) {
  17. throw error; // Re-throw the error if max retries reached
  18. }
  19. const delay = initialDelay * Math.pow(2, retryCount); // Exponential backoff
  20. await new Promise(resolve => setTimeout(resolve, delay));
  21. }
  22. }
  23. throw new Error("Max retries reached"); // Should not reach here, but good to have a fallback
  24. }
  25. // Example usage (replace with your actual API call)
  26. async function makeApiCall() {
  27. // Simulate an API call that sometimes fails
  28. const randomNumber = Math.random();
  29. if (randomNumber < 0.5) {
  30. throw new Error("API call failed!");
  31. }
  32. return "API response";
  33. }
  34. // Example: Retry the API call with 3 retries and an initial delay of 1000ms
  35. async function runScheduledRetry() {
  36. try {
  37. const result = await retryApiCall(makeApiCall, 3, 1000);
  38. console.log("API call successful:", result);
  39. } catch (error) {
  40. console.error("API call failed after multiple retries:", error);
  41. }
  42. }

Add your comment