0

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"
}
  • You basically can't make promises synchronous; these logs will always run before the `fetch` chain resolves. Embrace promises--chain from `then` or use `await` wherever code depends on the result. – ggorlen Aug 16 '22 at 23:27

1 Answers1

1

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 :)

MisieQQQ
  • 226
  • 1
  • 6