I’m learning node and express and I’m trying to implement a function that retrieves data from a csv file uploaded by the user.
The data should be processed first and then outputted to the console, but it instead outputs an empty array before processing it.
I followed examples of async/await from tutorials I found online but the issue persists and I’m not sure how to proceed.
app.on("event:file_uploaded", async(userDataPath)=>{
let result = await retrieveDataFromCsvFile(userDataPath);
console.log(result); //should be completed after retrieving data
});
function retrieveDataFromCsvFile(path){
return new Promise((resolve)=>{
console.log(`RETRIEVING DATA FROM: ${path}`);
const stream = fs.createReadStream(path);
const rl = readline.createInterface({input: stream});
let data = [];
rl.on("line", (row)=>{
data.push(row.split(","));
})
rl.on("close", ()=>{
console.log("Data Processed"); //should be completed first
})
resolve(data);
})
}
Outputs:
RETRIEVING DATA FROM: <filepath>
[]
Data Processed
>Solution :
You need to call resolve when you have the data you want.
At the moment you are:
- Registering a
lineevent handler - Registering a
closeevent handler - Calling
resolve
Some time later you will get line and close events that trigger their respective event handler functions … but by then you’ve already resolved the promise.
You need to determine what condition means your data is ready. At a guess, I’d expect that to be "When the callback to close is run" and call resolve then.