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...
  • @dandimrod
    link
    7
    edit-2
    1 year ago

    If you want to continue in the same function you’ll need to use async/await. In your case:

    async function yourFunctionName(){
        // previous logic
        const myVar = await fetch("myFile.json")
            .then(res => res.json());
        console.log(myVar);
        //rest of code executes...
    }
    

    Realize that you have to add async to your function and await to your fetch call. Also take into account that if your function returns anything, it’ll now return a Promise instead.