Ernesto G
Ernesto G

Reputation: 545

Checking a condition before making a fetch call

Lets say that I have to perform 4 calls to an api consecutively. When the call successfully ends and returns a response, I store the result of that call in a "cache" array. Before doing each fetch, I want to check if the url have been previously fetched by checking the url in the cache.If it is present in the cache, I just console.log the result, if not I will call the api.

Currently I have something similar to this code:

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)
})

The problem is that the check condition for the 4 urls gets evaluated before the fetch has been completed even once, so the cache is empty and the output is something like this:

[] //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

How can I handle this?

Upvotes: 1

Views: 787

Answers (1)

Bergi
Bergi

Reputation: 664538

Store the promise itself in the cache (which you can do immediately when making the request), not only the result as soon as it has arrived:

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

Upvotes: 1

Related Questions