1

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

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

6 Comments

Let me update the code snippet
Updated @Jacky.S
Thanks @hackape for your contribution.
My new question is how would I able to use assetsArray outside the .then() function. For example, after that code block, I am creating a new MongoDB object, that needs the assetsArray to be filled first
const records = await Promise.all(tasks); const recordIds = records.map(record => record._id);
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.