1

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 Answer 1

5

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.

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

2 Comments

can you set async to false or would just making it an ajax call with async:flase be better?
@JordanSimon - Using synchronous requests is a bad idea according to MDN: Note: You shouldn't use synchronous XMLHttpRequests because, due to the inherently asynchronous nature of networking, there are various ways memory and events can leak when using synchronous requests. (That's in the context of XMLHttpRequests, but the principle still applies since that's probably what jQuery uses under the hood.)

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.