1

I have a JSON file containing an array full of products and want to create a global array containing the JSON data.

When I tried the following code the array variable was printed before the data variable.

var array;

fetch("products.json")
.then(res => res.json())
.then(data => {
    console.log(data); // The data variable contains the data
            
    array = data;
})

console.log(array); // The array variable is undefined

So I tried to print the array variable after 500ms which is enough to fetch the data and the array variable was containing the data.

var array;

fetch("products.json")
.then(res => res.json())
.then(data => {
    console.log(data); // The data variable contains the data
            
    array = data;
})
setTimeout(() => {
    console.log(array); // The array variable contains the data
}, 500);

How can I print the array directly after the fetching is finished?

NVSS
  • 66
  • 1
  • 7
  • 4
    There's one, like, every day. Either use async/await (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/await) to make it neater, or put it inside the `then`, there really is no other way to _instruct javascript to wait until the data is there_. – somethinghere Jul 13 '22 at 14:08
  • 2
    Hard to understand asynchrony is – Jaromanda X Jul 13 '22 at 14:13
  • And every time I try to find one of the already existing answers to vote to close, I can't find any! – somethinghere Jul 13 '22 at 14:19

0 Answers0