How does one fetch some JSON data and save it into a variable and not continue executing the rest of the script until the fetch api has fetch the JSON data?

Here is my code which will return undefined in the console.

var myVar;

fetch("myFile.json")
	.then(res => res.json())
	.then(data => {
	myVar = data;
});
	
console.log(myVar)

//rest of code executes...
  • @gornius
    link
    3
    edit-2
    1 year ago

    I would recommend watching a video on how concurrency in JavaScript works. It should make everything clear for you about Promises and async await.

    https://youtu.be/8aGhZQkoFbQ

    Anyway, what do you want to achieve? There are many ways to go about it, at least in JS, where top level await is not a thing.

    Do you want fetched data render somewhere? Or maybe that’s part of your backend and you want to do something with it?