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

The code block below execute before my async await finishes

const getGroup = async (req, res) => {
  const { id } = req.params
  try {
    const group = await Group.findOne({ _id: id });    
    const groupNotesPromise = await group.group_notes.map( async (fileId) => {
      const file = await File.findById(fileId)
      return file;
    })
    const groupNotes = await groupNotesPromise.map( async (notePromise) => {
      await notePromise.then(res => console.log(res))
    })
    console.log(groupNotes)
  } catch (error) {
    console.log(err.message);
    res.status(400).json({ err: err.message });
  }
}

Hello guys, I have a function above, this is retrieving data from MongoDB.

However, I would like to know why would my console.log(groupNotes) be printed before the execution of the groupNotesPromise.map` above, as it has an await in the function.

Here is the console.log(groupNotes) and console.log(res) from the code above

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

[ Promise { <pending> }, Promise { <pending> } ]
{
  _id: new ObjectId("6496c645bf2bb491b931f082"),
  fileName: 'test',
  fileAwsReference: 'b4b71d06828d23d857b3611c2ce2480cf704f1fc1b9cb1879b563159631d162a',
  createdBy: new ObjectId("648bab3c8044efccc461ad1d"),
  createdIn: new ObjectId("648d7776284835591f536552"),
  __v: 0
}
{
  _id: new ObjectId("6496c9fafb91e60683fc812d"),
  fileName: 'waeewaea',
  fileAwsReference: '0e1f17f127f9a12a9e27d765bda1436297f0d58eb7d20f3e9dc8d39e64b58c5b',
  createdBy: new ObjectId("648bab3c8044efccc461ad1d"),
  createdIn: new ObjectId("648d7776284835591f536552"),
  __v: 0
}

>Solution :

The reason why console.log(groupNotes) is printed before the execution of groupNotesPromise.map is because you are using await inside the map callback function, but you are not waiting for the entire array of promises to resolve before logging the result.

const groupNotes = await groupNotesPromise.map(async (notePromise) => {
  await notePromise.then(res => console.log(res))
})

If you want to wait for all the promises to resolve before logging the result, you can use Promise.all()

const groupNotes = await Promise.all(groupNotesPromise);
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