Home > Enterprise >  Async await does not await
Async await does not await

Time:12-24

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 ?

CodePudding user response:

The result promises are being ignored in the forEach construct. You can replace it with a for...of as below:

async function getSortedAnimals() {
    const ids = [1,2,3];
    const sortedAnimals = [];
    for (const id of ids) {
        const animal = await findOneAndUpdate(
            {_id: id}
        );
        sortedAnimals.push(animal);
    }
    console.log(sortedAnimals);
}

async function findOneAndUpdate(o) {
    return o._id   1;
}

getSortedAnimals();

CodePudding user response:

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)
  • Related