0

I am trying to load data from a csv and store it in an array of objects. I know global variables are frowned upon but I can't think of a better way to store the data and access it from multiple functions.

Here is my code:

var mydata = new Array;
$(document).ready( function () {
    $.get('./datafile.csv', function(data) {
        var head = data.split("\n");
        for(var i = 1; i < head.length; i++){
            line = head[i].split(",");
            var obj = {
                index:i,
                img:line[0],
                caption:line[1],
                desc:line[2]
            };
            mydata.push(obj);
        }
        console.log(mydata); //1
    });
    console.log(mydata); //2
    //I then want to select various elements on my page and set some attributes to
    //an object in my data, but I can't since everything is undefined
});

At the first spot it logs my data correctly, but at second spot it logs an empty array. I read this article on global variables in JavaScript so I'm not sure what is going wrong.

Catherine
  • 241
  • 1
  • 2
  • 15

3 Answers3

2

The second part (//2) runs too soon. When $.get executes, it just starts the HTTP request to get the CSV, but doesn't wait for it to finish - that's why you need to pass that function(data) in. After the request finishes, the callback function gets called, and it's there that you should continue your initialization.

So, your code should look something like that below. (if you need to use the data elsewhere, you can keep on using the global, but it's not needed just for this)

$(document).ready( function () {
    $.get('./datafile.csv', function(data) {
        var mydata = [];
        var head = data.split("\n");
        // ...

        console.log(mydata); //1
        continueSetup(mydata); // 2
    });
});

function continueSetup(mydata) {
    // do what you need
}
xs0
  • 2,990
  • 17
  • 25
1

I think you might be getting confused about the order of what is happening in your code. First of all, there is nothing wrong with using a global variable like this, especially if you are accessing it multiple times throughout your page (using events and such). Secondly, the reason you are seeing an empty array at your "second" spot in code is because that spot (#2) is actually getting executed before your get function has received the data and before #1.

get is an asynchronous function, which means that it waits to receive a response, and then executes the code inside (including #1). However, #2 gets executed immediately, while your array is still empty.

Matt Spinks
  • 6,380
  • 3
  • 28
  • 47
  • This explanation makes a lot of sense, thanks! not accepting though since you did not provide a way to fix it – Catherine Dec 05 '17 at 22:15
  • Nothing needs to be "fixed" here. The way to "fix" it is to do the `console.log` inside your `get` function, which you are already doing. – Matt Spinks Dec 05 '17 at 22:25
0

At 2 the data will be same as what you initialized. At 1 the data will be the same as what you populated.

2 gets printed first if you have observed closely. This is because $.get is an asynchronous call and gets executed in the background. The callback you are providing to $.get will run after the GET request is either successfully completed or errored out.

Nandu Kalidindi
  • 6,075
  • 1
  • 23
  • 36