LearnFrenzy
Sign in Take a free test

Promises · Promises Coding Problems · Question 9

Cache promises to avoid duplicate requests in JavaScript Solution, output & explanation

  • Program
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 9 Back to Exercise

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.

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!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links