m9m9m
m9m9m

Reputation: 1721

how to call async function in .on event nodejs

I am reading a CSV file using csv-parser npm module createReadStream.

export default async function main() {
  const readstream = fs.createReadStream('src/working_file.csv');
stream.on('data', data => {
const val = await fun(param1, param2, param3);
   });
  fun(param1, param2, param3){
    return true;
  }
}

I have to call function fun with await but it is throwing me the error.await is only valid in async function. Can anyone help me how to fix this?

Upvotes: 0

Views: 1310

Answers (2)

squeekyDave
squeekyDave

Reputation: 972

The function that you await must return a promise.

export default async function main() {
  const readstream = fs.createReadStream('src/working_file.csv');
stream.on('data', async data => {
   try{
      const val = await fun(param1, param2, param3);
    } catch(err) {
    //handle error
    }

   });
  fun(param1, param2, param3){
    return new Promise((resolve, reject)=>{
         resolve(some_value)
    })
  }
}

Upvotes: 0

Enslev
Enslev

Reputation: 622

Just indicate that the callback function is async.

stream.on('data', async data => {
  // Do async stuff
})

Upvotes: 2

Related Questions