Exercise 6: Fetch with Retry Logic

Problem Statement

Function `fetchWithRetry(url, options, maxRetries)` banao jo fetch ko retry kare on failure. Example: fetchWithRetry("https://api.example.com/data", {}, 3)

Sample Output:

await fetchWithRetry("https://api.example.com/data", {}, 3)
// Retries up to 3 times on failure

Solution

const fetchWithRetry = async (url, options = {}, maxRetries = 3) => {
  let lastError;
  for (let i = 0; i < maxRetries; i++) {
    try {
      const res = await fetch(url, options);
      if (res.ok) return res;
      throw new Error(`HTTP ${res.status}`);
    } catch (err) { lastError = err; }
  }
  throw lastError;
};

Explanation

Overall Goal:

  • Fetch request ko retry karna on failure.

Real world:

  • Network resilience: retry failed requests.
  • API reliability: automatic retries.