Write cachedFetch(key) that starts a request only once per key – even if called again while the first request is still in flight – and drops failed requests from the cache so they can be retried.
Solution
main.js
let requests = 0;
const fakeApi = (key) =>
new Promise((resolve, reject) => {
requests++;
setTimeout(() => (key === "bad" ? reject(new Error("404")) : resolve(`data for ${key}`)), 10);
});
const cache = new Map();
function cachedFetch(key) {
if (!cache.has(key)) {
const p = fakeApi(key).catch((err) => { cache.delete(key); throw err; }); // do not cache failures
cache.set(key, p);
}
return cache.get(key);
}
Promise.all([cachedFetch("user"), cachedFetch("user"), cachedFetch("user")])
.then((r) => console.log(r[0], "| requests:", requests))
.then(() => cachedFetch("bad"))
.catch((e) => console.log("bad failed:", e.message, "| cached?", cache.has("bad")));
Output Verified by running it on Node.js
data for user | requests: 1
bad failed: 404 | cached? false
Caching the promise (not the value) means three simultaneous calls share one in-flight request. The catch inside cachedFetch removes failed entries and rethrows so callers still see the error.
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!
We use Google Analytics cookies to see how LearnFrenzy is used and make it better, and Google AdSense to keep it free.
No analytics or ad cookies are set until you accept. Privacy Policy
·
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!