Description
APIs can be slow or unreliable. To improve performance, we can cache API responses, but sometimes the API may fail.
In this challenge, you’ll create an async cache wrapper that:
- Returns cached data if the same request is repeated.
- Handles API errors gracefully.
- Supports
awaitfor async functions. - Expires cached results after a specified time.
Task
Implement a function cachedApi(timer) that returns an async function:
- Parameters
url→ API endpointoptions→ fetch options
- Behavior
- If the URL is in the cache, return cached data immediately.
- If not, call
fetch(url, options)and cache the JSON response. - If
fetchfails, throw the error to the caller. - After
timermilliseconds, remove the cache entry so a fresh call can happen.
Example Usage
const api = cachedApi(1000); // cache expires in 1 second
// First call → fetches from API
const data1 = await api("https://api.example.com/data");
// Second call (within 1s) → returns cached data
const data2 = await api("https://api.example.com/data");
// After 1 second → cache expires, next call fetches fresh data
setTimeout(async () => {
const data3 = await api("https://api.example.com/data");
}, 1100);
Hints
Hint 1
Use a Map or object to store cached responses.
Hint 2
Wrap the fetch call in a try/catch to handle errors.