首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何改进异步数据检索和缓存?

如何改进异步数据检索和缓存?
EN

Stack Overflow用户
提问于 2020-09-08 17:40:49
回答 2查看 496关注 0票数 2

我获得了以下代码,用于异步检索数据并缓存数据以达到性能优化的目的:

代码语言:javascript
运行
复制
let cache = {}
const optimizedFetch = async (url) => {
    if (url in cache) {
        // return cached result if available
        console.log("cache hit")
        return cache[url]
    }
    try {
        const response = await fetch (url)
        const json = response.json();
        // cache response keyed to url
        cache[url] = json
        return json
    }
    catch (error) {
        console.log(error)
    }
}

optimizedFetch("https://jsonplaceholder.typicode.com/todos").then(console.log)

上面的方法工作得很好,但是如果在等待第一个url的时候出现了对同一个url的第二个请求,那么就会触发第二个fetch。

你能告诉我如何改善这种情况吗?提前谢谢。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2020-09-08 18:44:42

代码语言:javascript
运行
复制
let cache = {};
let awaits = {};
const optimizedFetch = (url) => {
  return new Promise((resolve, reject) => {
    if (url in cache) {
      // return cached result if available
      console.log("cache hit");
      return resolve(cache[url]);
    }
    if (url in awaits) {
      console.log("awaiting");
      awaits[url].push({
        resolve,
        reject
      });
      return;
    }
    console.log("first fetch");
    awaits[url] = [{
      resolve,
      reject
    }];
    fetch(url)
      .then(response => response.json())
      .then(result => awaits[url].forEach(({
        resolve
      }) => resolve(result)))
      .catch(error => awaits[url].forEach(({
        reject
      }) => reject(error)))
      .finally(() => {
        delete awaits[url];
      });
  });
};

optimizedFetch("https://jsonplaceholder.typicode.com/todos")
  .then(({
    length
  }) => console.log(length));
optimizedFetch("https://jsonplaceholder.typicode.com/todos")
  .then(({
    length
  }) => console.log(length));

票数 2
EN

Stack Overflow用户

发布于 2020-09-08 18:24:03

只要把承诺作为一种价值。

工作实例:

代码语言:javascript
运行
复制
let cache = {}
let totalRequests = 0;

const optimizedFetch = async(url) => {
  if (cache[url]) return cache[url]; // return what we have

  totalRequests++;
  const fetchedRequest = fetch(url)
    .then(response => response.json())
    .then(json => {
      cache[url] = json; // <-- we replace "Promise" result with json result
      return json;
    });
  cache[url] = fetchedRequest; // <-- we keep Promise as a result

  return fetchedRequest;
}

for (let i = 0; i < 5; i++) {
  console.log('Setting request #', i);
  optimizedFetch("https://jsonplaceholder.typicode.com/todos").then(result => console.log('Requests:', totalRequests, 'Result:', result.length));
}

解释:

  • totalRequests只是为了测试的目的,它向我们展示了如果缓存中有一个答案,我们生成了多少“真实”的
  • --如果我们没有答案,就返回答案
  • --我们创建了新的fetch,并将其作为应答

来处理。

我的回答是被否决了,但我不明白为什么.它使用的是cache示例。请各位,如果你们投反对票,请评论上面,所以我会理解我的错误如果有的话。谢谢

票数 -2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/63799045

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档