Nadeem Khan
Nadeem Khan

Reputation: 171

Await is not waiting to read data from file?

I write the following code to read the data from the file and push into array. But attachments.length is printing 0 first and then data is loaded and print.

const fs=require('fs');
const util=require('util');
const files=['t1.csv','t2.csv','t3.csv'];
async getdata(){
     const read=util.promisify(fs.readFile);
     let attachments = [];
     async function run(file){
         let data=await read(file);
         attachments.push(data);
     } 
     for(let file of files){
         await run(file);
     }
     console.log(attachments.length);//should print 3
}

How to load the data first and then push correctly.

Edit: change the some part of code to use await. But loop break after first iteration without giving any error neither print my attchments.length .

Edit 2: problem resolved. Calling function should also need to be await. Thanks every one.

Upvotes: 2

Views: 1119

Answers (2)

Rafi Henig
Rafi Henig

Reputation: 6432

This is happening because run() should be awaited as well in this case, see async function

One approach is using IIFE:

(async file => {
    let data = await read(file);
    console.log(data);
    attachments.push(data);
})('/home/nadeem/Desktop/test.csv')

Upvotes: 3

Rob Johansen
Rob Johansen

Reputation: 5164

When you call an async function, it returns a promise that will eventually resolve with the value returned by the function (or reject with an uncaught exception thrown from within the function).

So you're trying to log the number of attachments before the run () function has finished. Here's what you need:

run('/home/nadeem/Desktop/test.csv')
  .then(() => console.log(attachments.length))

Upvotes: 1

Related Questions