Cannot access outside variables from the jquery get function

148 views Asked by At

I am trying to turn csv into associative array but the $.get function does not change the outside textData variable

function csvToArray(filename){

var textData;
var headers = new Array(),
    dataValues = new Array();

$.get(filename, function(data){
    textData = data;
});

var dataArray = textData.split('\n');
headers = dataArray[0].split(',');

for(var i = 1; i<dataArray.length; i++){
    var thisLine = dataArray[i].split(','),
        tempArray = new Array();

    for(var j = 0; j<thisLine.length; j++){
        tempArray[headers[j]] = thisLine[j];
    }

    dataValues.push(tempArray);
}

return dataValues;

}

Why is textData not being set?

1

There are 1 answers

2
Sushanth -- On BEST ANSWER

get is Async

So by the time textData is set , the remaining statements are already executed.

So consider moving the statements after the get to inside the callback, wherein the textData is populated and then processing can be done on it.