簡體   English   中英

如何從在 Node 中使用 fetch 的異步函數緩存數據

[英]How to cache data from async function that uses fetch in Node

我試圖看看是否有辦法緩存來自 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)
    }
}

例如,如果我讓某人在一分鍾內點擊我的路線 20 次,我希望輕松獲取數據並在 0.03 毫秒而不是 0.3 毫秒內返回響應。 目前,它總是使用 URL 來獲取數據。

這已經有一段時間了,但我同意@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');

異步函數不會阻止緩存結果。 您正在查看的庫可能無法處理承諾,但這里有一個基本的概念證明,可能有助於開始工作:

 let cache = {} const jsonFetch = 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[url] = json // cache response keyed to url return json } catch (error) { console.log(error) } } jsonFetch("https://jsonplaceholder.typicode.com/todos/1").then((user) => console.log(user.id)) // should be cached -- same url setTimeout(() => jsonFetch("https://jsonplaceholder.typicode.com/todos/1").then((user) => console.log(user.id)), 2000) // not in cache setTimeout(() => jsonFetch("https://jsonplaceholder.typicode.com/todos/2").then((user) => console.log(user.id)), 2000)

您只會第一個請求返回緩存值的請求中獲得緩存命中

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM