代码之家  ›  专栏  ›  技术社区  ›  Ernesto G

在进行提取调用之前检查条件

  •  1
  • Ernesto G  · 技术社区  · 6 年前

    假设我必须连续执行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
    

    我该怎么办?

    1 回复  |  直到 6 年前
        1
  •  1
  •   Bergi    6 年前

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

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