0

I have this code in Javascript:

var words = [];

d3.json("myFile.json", function(data) {
    words = data.words;
    console.log(words);  //Log output to console
});

console.log(words);  //Log output to console

The first console.log(words); shows an array of seven objects. But the second console.log(words); shows an empty array. So it looks like words outside of the d3.json function is not the same as words inside that function.

I also have tried to use console.log(window.words); outside of the function and it still shows an empty array.

How can I get the data that I have read from myFile.json in the d3.json function, outside of that function?

416E64726577
  • 2,214
  • 2
  • 23
  • 47
TJ1
  • 7,578
  • 19
  • 76
  • 119

1 Answers1

3

d3.json is an asynchronous function. That means that the code you pass is not executed immediately, but as a callback after the request for the JSON file returns. That is, a network request is sent for the file, but the normal flow of execution continues.

The console.log(words); outside d3.json is simply executed before the call returns and the array is populated.

Lars Kotthoff
  • 107,425
  • 16
  • 204
  • 204
  • Thanks for the answer. Is there a way I can wait until the array populated and then use it? – TJ1 Apr 20 '14 at 22:55
  • I tried to delay the second `console.log(words);` by adding: `var aa; for (var i = 0; i < 100000; i++) { aa= 10 + Math.random() * 90; }` before that but it didn't help! – TJ1 Apr 20 '14 at 23:24
  • 1
    You can use [queue](https://github.com/mbostock/queue), move you code into `d3.json` call or call a function and pass `words` to from inside the `d3.json` function. In addition to Lars comments [this question](http://stackoverflow.com/questions/9491885/csv-to-array-in-d3-js) might also help. – user1614080 Apr 20 '14 at 23:25
  • @user1614080 thanks for the comment, I did that and it worked, i.e I moved my code inside `d3.json` function. – TJ1 Apr 21 '14 at 04:24