0

I have code like this

 let newUrl = url.toString()
      let storedData = [];
      fetch(newUrl)
      .then((response) => {
       return response.json();
      })
      .then((data) => {
        storedData = data;   
      });
      console.log(storedData)

I would like to be able to get to the data from fetch, but even if I want the data to be added to the storedData list, the script throws an empty list anyway.

If I try to check the data I have with fetch in .then I normally get the answer I want.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
gravgor
  • 29
  • 5
  • See e.g. https://stackoverflow.com/q/14220321/3001761. _"If I try to check the data I have with fetch in .then I normally get the answer I want"_ - yes, that's how promises work. – jonrsharpe Sep 07 '22 at 19:32

1 Answers1

1

Async JS concept used that's why created the problem. Data is fetched everything is good but you add the data this time data is in the callback queue and the callback queue holds the data your data is already loaded because you initialize the array variable out of the async function.

Hamza Ali
  • 32
  • 6