Vue.js - await for a single record from CSV to be retrieved using 'csv-parse' package

225 Views Asked by At

In my Vue.js application, I had to parse CSV file and upload each line to the backend. I would like to do it asynchronously so that the reading of the next record takes place after the previous record is already uploaded (promise resolved).

import parse from 'csv-parse';

importCsv() {
  const parser = parse()
  
  let index = 0;
  parser.on('readable', async () => {
    let record = parser.read()
    if(record) {
      await new Promise((resolve) => setTimeout(resolve, 1000))
      index++
      console.log("record nr ",index)
    }
  })      
  
  parser.on('error', (err) => {
    console.log(err)
  })

  parser.on('end', () => {
    console.log("finish")
  })

  parser.write(this.fileContent)
  parser.end()
}

this.fileContent is a file content saved in my component as string.

Even if I put await statement before promise and async before readable event callback, it still not working as it should.

actual_output

Currently, the word 'finish' appears first, which means that parsing is over. Then, after 1 second, 9 console logs are displayed at once

I would like output with the record number to appear every 1 second, and then at the end the console log "finish".

0

There are 0 best solutions below