0

PLEASE help me, because JS is really killing me this time.

Everything was fine until I started to split my app into separate functions. Step one in my app is to get weather data. So I call getData function on window load. Response is fine, I get my data, I return them afterwards to the data variable. I console.log the data and array it is. But I can't acces array's values! Nor me nor some functions (d3.max() i.e.). I've tried everything but I have no clue what is going on.

enter image description here(Hope the print screen will explain you the problem better)

window.onload = function(){
  var data = getData( cities.poznan );  
  console.log(data);
  console.log(data[0]);
}

var cities = {
  poznan: "3088171",
  madrid: "3117735",
  barcelona: "3128760"
};

function round(n){
  return Math.round( n * 10) / 10;
}

function getData(id){
  var key = "22421a7c9d3efxxxxxx2b71394";
  var url = "http://api.openweathermap.org/data/2.5/forecast/daily?id=" + id + "&units=metric&cnt=7&appid=" + key;
  var data = [];

  d3.json(url, function(response){

    response.list.forEach(function(el){
      data.push( el.temp.day );
    });
  });

  return data;

}
0blivion6
  • 51
  • 1
  • 6
  • 2
    `d3.json` is **asynchronous**. You can't return data that hasn't been received yet – charlietfl Feb 10 '17 at 20:57
  • Yes! As @charlietfl pointed, `d3.json` is async. When you log data[0], it is undefined because data hasn't been pushed to the array. The reason you can see the content of the data array when you log it is because chrome dev tools "populates" it for you when data is available – fmilani Feb 10 '17 at 21:03
  • @charlietfl Thank you! I get it now and it works. But these console.log results were so confusing. – 0blivion6 Feb 10 '17 at 21:24

0 Answers0