2

I am trying to store my response from d3 async call to a global variable. I have gone through the discussions why a variable is not updated with aysnc calls because of the time they take to return the responses. I have tried something like this

var x = []; // global variable 
d3.json("url", function(response)
{
callback(response); //passing response to call back 
});

function callback(data)
{
     x = data; // assigning data to x ;
}

$(document).ready(function () {    
console.log(x);
});

Still my x is undefined. can anybody help with this ! I have tried couple of solutions from other posts but nothing worked. How can i access my x[] in $(document).ready function(function()){}

hhhh4
  • 43
  • 1
  • 9
  • 1
    where are you using x? – eko Jun 06 '16 at 05:35
  • In the first line, you only need `var x;`. And, as echonax asked, if you use x outside `function callback` it will probably return undefined, because the code outside those 2 functions will run faster. – Gerardo Furtado Jun 06 '16 at 05:44
  • 1
    @GerardoFurtado actually if OP is initializing x with an empty array and sets it to something only inside callback. Only the data from the callback can make it undefined, otherwise it'd be an empty array. But I don't think that's what the OP meant :P – eko Jun 06 '16 at 05:50

0 Answers0