Skip to content Skip to sidebar Skip to footer

D3.JS JSON Data Import - Not In Global Scope

I have a json: { 'temp_data': [10,15,20] } I am trying to import it: var temp_data; //Importing from JSON if(true){ d3.json('graph.json', function(error, graph) {

Solution 1:

The callback passed into d3.json() runs asynchronously: https://github.com/d3/d3/wiki/Requests#d3_json

This means your second console.log() actually runs before "graph.json" has been retrieved, and therefore before your global variable is populated. You need to do your work with this data inside the callback instead.


Solution 2:

Just to add some information to the accepted answer: if you wait just a little bit, you can use your console.log outside the callback:

setTimeout(function(){
    console.log("Outside the callback: " + temp_data);
}, 1000);      

Check this plunker: https://plnkr.co/edit/zTg6Y6KSVedIBT2tVCu9?p=preview

The reason for this was already explained in the accepted answer: being asynchronous, the code below d3.json runs almost immediately, that is, it doesn't wait for d3.json to finish.


Post a Comment for "D3.JS JSON Data Import - Not In Global Scope"