bucho@lemmy.onetoJavaScript@programming.dev•write to variable with fetch api before rest of script executes (client side)English
3·
1 year agoYour 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);
WTF is up with all the NSFW tags, and the massive ChatGPT-like spam?