首页 > 解决方案 > 如何实现在内部范围内缓存/记忆请求结果的功能

问题描述

我试图实现一个函数来发出缓存结果的请求。

要求是:

如果不使用类,我找不到任何方法将结果存储在函数范围内。我尝试了以下代码,但我意识到this.responses它实际上是一个全局变量window.responses。有什么办法吗?

function cachedRequest(url) {
    if (!this.responses) this.responses = {} // This is actually a global variable at window.responses, cant use it
    return new Promise((resolve, reject) => {
        const cachedValue = this.responses[url]
        if (cachedValue) {
            console.log('returning cached result')
            return resolve(cachedValue)
        };
        fetch(url).then(res => {
            console.log('fetching and caching result')
            this.responses[url] = res
            return resolve(res)
        })
    })
}

const URL = "https://pokeapi.co/api/v2/pokemon/ditto/"

cachedRequest(URL).then((response) => {
    console.log({response})
    cachedRequest(URL)
})

标签: javascriptcachingpromisescopeclosures

解决方案


您可以编写一个记忆函数,该函数在已使用的参数的闭包中进行跟踪。您可以在函数中注入每个回调memo以保持存储打开。

它还使您能够注入任意数量的参数并使您的代码非常灵活。

const memo = (callback) => {
  const cache = new Map();
  return (...args) => {
    const selector = JSON.stringify(args);
    if (cache.has(selector)) return cache.get(selector);
    const value = callback(...args);
    cache.set(selector, value);
    return value;
  };
};

const cachedRequest = memo(fetch);
const URL = "https://pokeapi.co/api/v2/pokemon/ditto/";

cachedRequest(URL).then((response) => {
  console.log(response);
  cachedRequest(URL);
});

推荐阅读