如何防止在node.js

时间:2017-11-17 15:45:47

标签: javascript node.js caching promise fetch-api

我有x次调用后端。其中一些是相同的URL。我正在缓存结果。但我的问题是,如果我使用相同的URL立即调用loadCached两次(或几次),它实际上也会调用两次fetch,因为在解析第一次获取之前缓存没有url。因此,只有在成功完成一次提取(=已解决)时,缓存才有效。我怎样才能改进代码以等待第一次获取被解析以避免重复查询?

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;
    });
}

我使用promise.all()等待loadCached解析。

1 个答案:

答案 0 :(得分:4)

你需要缓存整个承诺:

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())
}

另请注意,要使用地图设置新值,您需要使用set方法,cache[url]不正确。