this post was submitted on 05 Aug 2023
8 points (100.0% liked)

JavaScript

1700 readers
1 users here now

founded 1 year ago
MODERATORS
 

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...
top 4 comments
sorted by: hot top controversial new old
[–] [email protected] 7 points 1 year ago* (last edited 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.

[–] [email protected] 4 points 1 year ago* (last edited 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?

[–] [email protected] 3 points 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);
[–] [email protected] 2 points 1 year ago

Put the rest of the code into then.

load more comments
view more: next ›