I am trying to read the JSON from a link, then save the json data as a variable accessible in the global scope. However, currently the variable is not being updated whenever the Promise is carried out. Attached is my JavaScript code:
let json;
fetch('test.json')
.then((response) => response.json())
.then((data) => {
json = data;
});
console.log(json);
console.log(json.name);
And attached is the ‘test.json’ file:
{
"name": "Alex C",
"age": 2,
"city": "Houston"
}
>Solution :
the value in let json;
is updated but asnchronously. And the console.logs are fired synchronously depending what you want to do with the data later you can access it in many ways using Promises which btw fetch returns 🙂