I'm trying to use async and await in a function that uses a forEach loop. Annoyingly I can't get it to work. What should happen is it takes an array of event docs, loops through them, adds in some extra data, then pushes them to the events array. This events array is then returned from the original function. Here is my code:
async function getEvents() {
...
var events = []
await addExtrasToDocsForUser(docs, currentUserId, events)
return events
}
var addExtrasToDocsForUser = (docs, currentUserId, events) => {
return docs.forEach(async (eventDoc) => {
const event = await addExtrasToDocForUser(eventDoc, currentUserId)
events.push(event)
})
}
What actually happens is the getEvents() function returns events as an empty array before the forEach loop has completed. How do I fix this?