Home > database >  Javascript wait on async forEach loop
Javascript wait on async forEach loop

Time:09-06

I am creating MongoDB records based on user inputs, and then for each new object created, I am pushing the object ID into an array. My problem is my console.log statement in the last line returns empty. So How I could wait on the forEach execution to be over so I have the updated assetsArray, any help is appreciated! Here is my code:

let assetsArray = [];
if (assets) {
  JSON.parse(assets).forEach(asset => {
    Image.create({
      organization: organizationID,
      imageName: asset.imageName,
      imageDescription: asset.imageDescription ?? null,
      imagePath: asset.imagePath
    }).then(record => {
      console.log(record)
      assetsArray.push(record._id)
    })
  })
}
console.log(assetsArray)

CodePudding user response:

You can use Promise.all for your case

const tasks = JSON.parse(assets).map(asset => {
  return Image.create({
    organization: organizationID,
    imageName: asset.imageName,
    imageDescription: asset.imageDescription ?? null,
    imagePath: asset.imagePath,
  })
});

Promise.all(tasks).then((records) => {
  return records.map(record => {
    console.log(record)
    return record._id
  })
}).then(assetsArray => {
  console.log(assetsArray)
})

  • Related