Exercise 9: Fetch with Timeout and Fallback

Problem Statement

Function `fetchWithTimeout(url, options, timeout, fallback)` banao jo timeout pe fallback return kare. Example: fetchWithTimeout(url, {}, 5000, () => getCachedData())

Sample Output:

await fetchWithTimeout(url, {}, 5000, () => getCachedData())
// On timeout: returns cached data

Solution

const fetchWithTimeout = async (url, options, timeout, fallback) => {
  try {
    const controller = new AbortController();
    const timeoutId = setTimeout(() => controller.abort(), timeout);
    const res = await fetch(url, {...options, signal: controller.signal});
    clearTimeout(timeoutId);
    return res;
  } catch (err) {
    if (err.name === "AbortError") return fallback();
    throw err;
  }
};

Explanation

Overall Goal:

  • Fetch ko timeout kare with fallback.

Real world:

  • Timeout handling: fallback data.
  • Resilience: cached fallback.