Pet*_*maa 3 javascript caching node.js promise fetch-api
我要对后端进行 x 次调用。其中一些指向相同的 URL。我正在缓存结果。但我的问题是,如果我使用相同的 URL 立即调用 loadCached 两次(或多次),它实际上也会调用两次 fetch,因为在第一次 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;
    });
}
Run Code Online (Sandbox Code Playgroud)
我正在使用 promise.all() 等待 loadCached 解决。
您需要缓存整个承诺:
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())
}
Run Code Online (Sandbox Code Playgroud)
另请注意,为了使用 map 设置新值,您需要使用set方法,这cache[url]是不正确的。