0

I'm trying to pass json content from a local file to a variable in order to feed dropdown lists dynamically. I've got the code below that works just fine if I hard code the json data, but I struggle to initialize the variable that receives the json from the local file... I fetch it, print it in the console, but my var remains undefined afterwards.

https://jsfiddle.net/ssoj_tellig/zo85r30x/10/

// test to pass json content to var mydates:
var mydata;    
fetch("{% static 'dates.json' %}")
.then(function(u){return u.json();})
.then(function(json){mydata = json; console.log(mydata)})

// test to see if mydates is correctly initialized, this should print in the console: 2018, 2019, 2020 ... not working
for (let year in mydata){                  
    console.log(year)
}

I've read the following articles, but to no avail (I still struggle to understand how to fix it):

What is the scope of variables in JavaScript?

How do I return the response from an asynchronous call?

Many thanks for your help !

2
  • 1
    Put your for loop inside the last .then() callback. Commented Jan 4, 2021 at 15:24
  • 1
    This might also help to how to think about callbacks: felix-kling.de/blog/2019/… Commented Jan 4, 2021 at 15:28

1 Answer 1

1

fetch calls are handled asynchronously, while your for-loop is invoked synchronously. To fix this, you should include the loop in the last .then call.

fetch("{% static 'dates.json' %}")
  .then(function(u){return u.json();})
  .then(function(json){
    for (let year in mydata){                  
      console.log(year);
    }
  });
Sign up to request clarification or add additional context in comments.

3 Comments

or better yet, define a function that does whatever you want - and use it in the then.
@sheriffderek: Why would that be better?
Because it will encapsulate the logic, and the .then block won't turn into a total mess. It'll also force the designer to abstract the meaning into a clear and concise bit of instructions that is compostable. jsfiddle.net/sheriffderek/c5se17fm But hey - maybe it's not better. You could write all the code with no functions.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.