Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I update a variable in the global scope inside of a promise?

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"
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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 🙂

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading