1

It seems, due to asynch nature of the callback while calling d3.csv, the variables inside the callback are not accessible outside. Is there a workaround to this?

Here is my code -

var cprices;

d3.csv("../data/crudeprices.csv", function(data){

cprices = data;

getCrudePrices(data);

});

function getCrudePrices(data){

    for(var i = 0; i < data.length; i++) {

        //cprices.push(data[i].price);

        //console.log(cprices[i]);

    }

}

console.log("cprices " + cprices);

I want to read the csv file and load the data into an array outside the callback. But it seems this is not supported. Is there a solution/workaround to this? Ref. - csv to array in d3.js

Community
  • 1
  • 1
Sumod
  • 3,806
  • 9
  • 50
  • 69
  • did you try it? It should work, because you call the function in the callback. Although I don't know what you intend with 1. assigning data to cprices, then pushing data into cprices. – Ido Tamir Sep 18 '13 at 11:23
  • You simply declare the variable that you store the data in outside the scope of the async callback. – Lars Kotthoff Sep 18 '13 at 11:33
  • I have tried it many times. But it is not working. I tried pushing data after I saw the assignment was not working. I am also declaring the variable cprices outside d3.csv. updated the code with the line where I declare the variable – Sumod Sep 18 '13 at 17:41

1 Answers1

0

Possible solution: The d3.csv(...) call is asynchronous, so it may not be executed completely by the time you get to "console.log(...)"

Suggest, as an intermediate hack, put a sleep timeout for a few seconds, and see if that helps.

If it does, you would probably want to restructure your code to take into account the asynchronous nature of the call. This could mean handling all of your logic from inside the d3.csv() call

cmonkey
  • 4,256
  • 1
  • 26
  • 46