0

I have a use case where a dataset has to be iterated and loaded into the database. I am using an async function for the purpose,

    const dataset = []
    dataset.forEach(async(data) => {
    const filter = {id:data.id}
    const count = await datamodel.find(filter).count();
    
    if(count===0){
          /*Insert Data*/
          datamodel.save(data)}
    else{
         /* Update Data*/
         datamodel.upsert(data)}
    })

But the database inserts are not as expected. Only the last entry of the dataset gets updated multiple times which is due to async and await in code.

How can I rewrite the code to perform the desired operation in a sequential fashion?

Note: .then() also has the same output.

VinayGowda
  • 155
  • 2
  • 12
  • Just write a normal loop `for (const data of dataset)`. Or even `for (let i = 0; i < dataset.length; i++)`. What is the issue with using bog standard loops? – VLAZ Jun 03 '21 at 19:21
  • use a `for` loop instead of `forEach` method – Sergio Tulentsev Jun 03 '21 at 19:21
  • 2
    Does this answer your question? [Using async/await with a forEach loop](https://stackoverflow.com/questions/37576685/using-async-await-with-a-foreach-loop) – Omri Attiya Jun 03 '21 at 19:21
  • No ,for (const data of dataset) and for (let i = 0; i < dataset.length; i++) didn't work for me as my code had multiple await within for loop. I had to refactor the code to make it work – VinayGowda Jun 12 '21 at 08:20

0 Answers0