gpt4 book ai didi

javascript - 在进行获取调用之前检查条件

转载 作者:行者123 更新时间:2023-11-30 20:00:12 26 4
gpt4 key购买 nike

假设我必须连续执行 4 次 API 调用。当调用成功结束并返回响应时,我将该调用的结果存储在“缓存”数组中。在每次获取之前,我想通过检查缓存中的 url 来检查该 url 是否以前被获取过。如果它存在于缓存中,我只是控制台记录结果,如果没有,我将调用 api。

目前我有类似这段代码的东西:

const requests = [url1, url2, url3, url2]
const cache = []

function getData(url) {
return fetch(url)
.then(function(response) {
return response.json()
})
}

function checkCache(url) {
return cache.filter(function (item) {
return item.url === url
})
}

function callApi(url) {
const cacheData = checkCache(url)
console.log(cacheData)
if (cacheData.length > 0) {
console.log (cacheData)
}
else {
getData(url).then(function (data) {
console.log(data)
cache.push(data)
})
}
}

requests.forEach(function(url) {
callApi(url)
})

问题是 4 个 url 的检查条件在抓取完成之前就已经评估了一次,所以缓存是空的,输出是这样的:

[] //checks the cache 4 times and its empty x 4
[]
[]
[]
data //calls the api
data //calls the api
data //calls the api
data //calls the api, but this data should come from the cache since the url2 have been already called

我该如何处理?

最佳答案

将 promise 本身存储在缓存中(您可以在发出请求时立即执行),而不仅仅是在结果到达时立即存储:

const cache = new Map();
function callApi(url) {
if (!cache.has(url))
cache.set(url, getData(url));
return cache.get(url);
}

关于javascript - 在进行获取调用之前检查条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53462340/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com