假设我必须连续执行4次api调用。当调用成功结束并返回响应时,我将该调用的结果存储在“缓存”数组中。在执行每次提取之前,我想通过检查缓存中的url来检查之前是否提取过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)
})
[] //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
我该怎么办?