Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Async await does not await

I am trying to loop through an array and for each id, update the model, then push the result in another array

this is my code :

async function getSortedAnimals() {
  var i = 0;
  var sortedAnimals = [];
  ids.forEch(async (id) => {
    i++;
    const animal = await this.animalModel.findOneAndUpdate(
      { _id: id },
      {
        $set: {
          order: i,
        },
      },
    );
    sortedAnimals.push(animal);
  });
  console.log(sortedAnimals);
  return sortedAnimals;
} //function

when I console log, the array is empty, I don’t know why ! it’s like it does not await for the loop to end.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

any suggestions ?

>Solution :

because you are loging the array before pushing objects to it

itterations are async but not the global loop, however you can use for await

var sortedAnimals = [];
var i = 0;
for await (const id of ids) {            
i++;
const animal = await this.animalModel.findOneAndUpdate(
{ _id: id },
{
$set: {
order: i,
},
);

i++;
}
console.log(sortedAnimals)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading