How to prevent fetch with same URL being called twice in node.js

Viewed 2741

I have x number of calls to be made to back-end. Some of them are to same URLs. I am caching the results. But my problem is thatIf I call loadCached immediately twice (or several times) with a same URL, it will actually call fetch twice as well, as cache does not have url before the first fetch is resolved. So, caching works only when one fetch is successfully completed (=resolved). How could I improve the code to wait for the first fetch to be resolved to avoid duplicate query?

function loadCached(url) {
  let cache = loadCached.cache || (loadCached.cache = new Map());

  if (cache.has(url)) {
    return Promise.resolve(cache.get(url)); // (*)
  }

  return fetch(url)
    .then(response => response.text())
    .then(text => {
      cache[url] = text;
      return text;
    });
}

I'm using promise.all() to wait for loadCached to resolve.

1 Answers

You need to cache entire promise:

function loadCached(url) {
  let cache = loadCached.cache || (loadCached.cache = new Map());
  let promise;

  if (cache.has(url)) {
    promise = cache.get(url)
  } else {
    promise = fetch(url)
    cache.set(url, promise)
  }

  return promise
    .then(response => response.text())
}

Also note that in order to set new value with map, you need to use set method, cache[url] is incorrect.

Related