javascript - 在进行 fetch 调用之前检查条件
问题描述
假设我必须连续执行 4 次对 api 的调用。当调用成功结束并返回响应时,我将该调用的结果存储在“缓存”数组中。在进行每次获取之前,我想通过检查缓存中的 url 来检查该 url 是否已被先前获取。如果它存在于缓存中,我只需 console.log 结果,如果没有,我将调用 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 的检查条件在 fetch 完成之前被评估一次,所以缓存是空的,输出是这样的:
[] //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);
}
推荐阅读
- unity3d - 如何在 Unity 中加入精灵
- javascript - 通过 Javascript 向 Json 添加数据
- javascript - DataTable 库未在表上建立
- jupyter-notebook - Anaconda 不会更改 Jupyter 的环境,必须重新启动。(赢 10)
- ruby-on-rails - 如何使用 Ruby on Rails 处理数据库可伸缩性
- r - 在 purrr::map 中重新创建小标题
- javascript - 在网络应用程序中使用 Firebase Firestore,我可以排除某些字段被返回吗?
- python - 我可以在 Python 中查看词法分析器和解析器的中间结果吗?
- spring - 读写头休息控制器
- asp.net-core - Aspnet core 3 -- 如何从控制器返回作为字符串生成器创建的文本或 csv 文件?