8

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...
no comments (yet)
sorted by: hot top controversial new old
there doesn't seem to be anything here
this post was submitted on 05 Aug 2023
8 points (100.0% liked)

JavaScript

2141 readers
1 users here now

founded 2 years ago
MODERATORS