The first parameter within forEach
is it's own function. To use await
within a function the function MUST be marked as async
. It works in the loop because there is no new function, and presumably the function you are running the loop in is marked as async
. So, to make the forEach
work, you need to do:
names.forEach(async (name) => {
images.push(await loadImage(name));
})
However, that's not the best thing. Really you want to gather the promises and then wait for them all to finish:
const promises = names.map(name => loadImage(name));
const images = await Promise.all(promises);