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?

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks for the answer. Is there a way I can wait until the array populated and then use it?
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!
You can use 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 might also help.
@user1614080 thanks for the comment, I did that and it worked, i.e I moved my code inside d3.json function.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.