如何在 Node 中缓存使用 fetch 的异步函数中的数据

fla*_*432 2 javascript arrays memcached json object

我试图看看是否有一种方法可以缓存来自 fetch 异步调用的 json 响应,可能使用 LRU。

我尝试过使用多个包,例如 node-cache 和 lru-cache,但我认为它们不起作用,因为我的函数是异步的。

这就是我的 fetch 函数的基本样子:

const jsonFetch = async (url) => {
    try {
        const response = await fetch (url)
        const json = await response.json();
        return json
    }
    catch (error) {
        console.log(error)
    }
}
Run Code Online (Sandbox Code Playgroud)

例如,如果我让某人在一分钟内点击我的路线 20 次,我希望轻松获取数据并在 0.03 毫秒(而不是 0.3 毫秒)内返回响应。目前,它始终使用 URL 来获取数据。

Pao*_*olo 5

这已经有一段时间了,但我同意@sleepy012 的评论。如果我想避免并行调用,技巧应该是缓存承诺,而不仅仅是值。所以这样的事情应该有效:

let cache = {}
function cacheAsync(loader) {
  return async (url) => {
    if (url in cache) {                    // return cached result if available
        console.log("cache hit")
        return cache[url]
    }
    try {
        const responsePromise = loader(url)
        cache[url] = responsePromise
        return responsePromise
    }
    catch (error) {
        console.log('Error', error.message)
    }
  };
}


function delayedLoader(url) {
  console.log('Loading url: ' + url)
  return new Promise((r) => setTimeout(r, 1000,'Returning ' + url));
}

const cachedLoader = cacheAsync(delayedLoader);

cachedLoader('url1').then((d) => console.log('First load got: ' + d));
cachedLoader('url1').then((d) => console.log('Second load got: ' + d));
cachedLoader('url2').then((d) => console.log('Third load got: ' + d));
cachedLoader('url2').then((d) => console.log('Fourth load got: ' + d));
console.log('Waiting for load to complete');
Run Code Online (Sandbox Code Playgroud)