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...
  • bucho@lemmy.one
    link
    fedilink
    English
    arrow-up
    3
    ·
    1 year ago

    Your variable myVar doesn’t get defined until fetch receives the results, but fetch is an asychronous function, so console.log runs before myVar is defined.

    If you want to wait for the results of an asynchronous function before proceeding with execution, you need to use the await keyword:

    let myVar = await fetch("myFile.json").then(res => res.json());
    
    console.log(myVar);