首页 > 解决方案 > 在进行 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

我该如何处理?

标签: javascriptecmascript-6es6-promise

解决方案


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

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

推荐阅读