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

Javascript wait on async forEach loop

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)

>Solution :

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

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)
})
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