0

I am experiencing a strange behavior when I read csv file inside my script (my first attempt at reading CSV in D3). I am unable to access the data inside the script yet I am able to see it in the console. My CSV file as two columns of data with 'time" and 'pos_n' as headers. Here is my code:

var myData = []
d3.csv("my_sample.csv", function(data) {
        myData = data.map(function(d){
            return [+d["time"], +d["pos_n"]];
        })});

    console.log("from inside the code, length of myData: ", myData.length)

Here is the output from console: Output from console

Not sure how to make my code see myData array. Any pointers would be greatly appreciated.

Thanks!

1 Answer 1

1

d3.csv() is an asynchronous function which reads cvs file and returns the result via a callback. When you try to read myData right after calling d3.csv() method it prints '0' because the callback function(data) hasn't been executed yet and myData array is still empty.
You can see the expected output in the console because when you input commands manually the callback was already fired and new data is stored in myData array. This is a typical issue in Javascript due to its asynchronous execution. The easiest way to make your code see new data is to put it inside the callback function:

  var myData = []
  d3.csv("my_sample.csv", function(data) {
          myData = data.map(function(d){
              return [+d["time"], +d["pos_n"]];
          })
  // your code goes here
  });

If you are writing a complex app it's better to use libraries such as async.js or native Promises to structure your application.
You can read more on asynchronous nature of JavaScript here: https://github.com/getify/You-Dont-Know-JS/blob/master/async%20&%20performance/README.md#you-dont-know-js-async--performance

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

1 Comment

I see why the codes I looked at wrap everything with d3.csv, like what you did above. Thanks for the answer, that make sense now.

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.