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 !

Joss
  • 197
  • 1
  • 5
  • 18

1 Answers1

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);
    }
  });
CerebralFart
  • 3,336
  • 5
  • 26
  • 29
  • 1
    or better yet, define a function that does whatever you want - and use it in the then. – sheriffderek Jan 04 '21 at 15:27
  • 2
    @sheriffderek: Why would that be better? – JavaScript Jan 04 '21 at 15:38
  • 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. https://jsfiddle.net/sheriffderek/c5se17fm/ But hey - maybe it's not better. You could write all the code with no functions. – sheriffderek Jan 04 '21 at 15:57