Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Promises and Async/Await don't seem to do anything in Express/node

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You need to call resolve when you have the data you want.

At the moment you are:

  1. Registering a line event handler
  2. Registering a close event handler
  3. 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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading