Seeding model.save() - asynchronous problem


#1

Hey guys,
I try to save a .csv file into my database. For reading csv row by row i use fast-csv. For every row, i want to create a database entry.

This is my code inside the SeedFile.

class StationSeeder {
  async run () {
    try {
      csv.fromPath(file, {delimiter: ';', headers: true})
      .on("data", function(data){
          console.log(data);
          let station = new Station()
          station.name = data[0]
          station.save()
      })
      .on("end", function(){
          process.exit(0)
      })
    } catch (error) {
      console.error(error);
    }
  }
}

Reading csv file works fine - but it creates no database entries. I guess it is because of the asynchronous behaviour, station got overritten before station.save() could create the entry.
I know i should use await station.save(), but that gives me an error:

await station.save()
^^^^^^^

SyntaxError: Unexpected identifier

Makes sense, because I can use await only with async, but the fast-csv method is not async I guess.

I have no idea how to solve that problem so I would appreciate your help! :slight_smile:


#2

Your callback must be async.

May you try

csv.fromPath(file, { delimiter: ';', headers: true })
  .on('data', async function (data){
    
    let station = new Station()
    station.name = data[0]
    await station.save()
  })

#3

Run the seed command with --keep-alive command.

adonis seed --keep-alive

#4

Thank you both for your solutions! :slight_smile:
First one does not worked for me in this case, but I solved it by using an explicitly synchronous reader.

Next time I will try yout solution virk, thank you.