I am loading a CSV file from an external (web) source using PapaParse, which is constructed as an array contained within an object. This array is constructed as follows:
hazard: "Pepe"
impact: "PeepoLaugh"
issued: "11A Sunday"
person: "Pepe"
phenom: "Sadge"
polyid: 1
summary: "Lots of Text"
timing: "1P-4P Sunday"
The relevant functions to execute this process are as follows:
function handleParsedData(data) {
console.log('Parsed data:', data);
return data;
}
function downloadCSV(callback) {
Papa.parse("/oath/to/file.txt", {
download: true,
header: true,
delimiter: "|",
dynamicTyping:
complete: function(results) {
var parsedData = results.data;
handleParsedData(results.data);
callback(parsedData);
}
});
}
function exportedCSV() {
parsed = downloadCSV(function(parsedData) {
console.log(parsedData);
return parsedData
});
}
var exports = exportedCSV();
console.log(exports);
Upon inspecting the console log messages, I can verify that the callback function downloadCSV works correctly, which triggers a console message of this object and its array from the function handleParsedData call. To double check that this works properly, I also verified a second console message of the identical object and its array contained inside the function exportedCSV call.
My problem extends to using this object and its array outside of this function. I’ve assigned a variable exports, which is attached to the exportedCSV call. When I inspect this variable in the console log, it returns as undefined. What steps can I take to use this array outside of the function?
>Solution :
You can convert your downloadCSV() to an async function and use it with await or then() to get your parsed result:
async function downloadCSV() {
return new Promise((complete, error) => {
Papa.parse("/oath/to/file.txt", {
download: true,
header: true,
delimiter: "|",
dynamicTyping: ???,
complete: result => complete(result.data),
error
});
});
}
(async()=>{
var exports = await downloadCSV();
console.log(exports);
})();
// or
downloadCSV().then(exports => console.log(exports));