I'm trying to read a TSV data into an array and this async
function loads the rows just fine, but the rows.push(row)
is still delayed when I'm trying to get the rows outside the function.
Is there a way I can get the row data for use outside this function? I've tried promises, but it seems like they still need to be within an async function.
I'm looping through multiple files and reading the data for each, and I need to wait until all data is loaded to continue, so I don't think it makes sense to wrap everything else in a callback...
const csvToJson = require("csvtojson");
var rows = [];
const getRows = async (fileName) => {
const csvData = await csvToJson({
delimiter: "\t",
trim: true
}).fromFile(fileName);
csvData.forEach((row) => {
rows.push(row);
});
return rows;
};
getRows("myfile.tsv");
console.log(rows.length); // prints 0
setTimeout(function() {
console.log(rows.length);
}, 2000); // prints expected num of rows
// do something else with rows
doSomething(rows);
Alternatively, using callback, but I get a pending promise in return. I know I can resolve it with then
, but that doesn't help me outside of then
.
const getRows = async (callback, fileName) => {
const csvData = await csvToJson({
delimiter: "\t",
trim: true
}).fromFile(fileName);
let rows = [];
csvData.forEach((row) => {
rows.push(row);
});
return callback(rows);
};
// returns a pending promise
var csvData = getRows(rows => {
console.log("Rows in callback: " + rows.length); // expected length
return rows;
}, "myfile.tsv");
// do something else with data
doSomething(csvData);