I am using Papa Parse to parse a csv file. In "complete" I try to assign the results, an array of objects, to a variable that I declared outside of my call to Papa Parse's parse function. The variable is fine inside of the function but undefined outside. I tried this also with a string and integer but the variable still is undefined outside of the function.
var data;
for (var i = 0, f; f = files[i]; i++) {
if (f.type == 'application/csv' || f.type == 'application/vnd.ms-excel' || f.type == 'text/csv') {
Papa.parse(f, {
header: true,
dynamicTyping: false,
complete: function(results) {
console.log("Completed parsing results", results);
data = results.data.slice(0); //I tried other simple values here, such as "test"
console.log("Data after assigned value.", data); //Here the data is correctly assigned to the variable
}
});
console.log("Value of data outside function.", data); //Undefined??
}
}
Parsing a file is a asynchronous, which is why your last console.log line doesn't have any results: it executes before parsing is complete. Your handling of the results must happen inside or after the complete
callback.