Async await does not await

Advertisements

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.

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)

Leave a ReplyCancel reply