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?