I am trying to fetch data for a list of user IDs using forEach but the function returns before any of the async calls finish.
async function getUsers(ids) {
let results = []
ids.forEach(async (id) => {
const res = await fetch(`/api/users/${id}`)
const data = await res.json()
results.push(data)
})
return results
}
getUsers([1, 2, 3]).then(console.log)
I checked the MDN docs on forEach and noticed it does not wait for promises, so I tried adding await directly in front of the forEach call, but that just throws a syntax error since forEach itself is not async.
async function getUsers(ids) {
let results = []
await ids.forEach(async (id) => {
const res = await fetch(`/api/users/${id}`)
results.push(await res.json())
})
return results
}
That silences the error but results is still empty when logged. I also tried logging inside the callback and confirmed the fetches do eventually complete, just after getUsers has already returned. What is the correct pattern here so getUsers actually waits for all three requests before returning.