-1

Why does

names.forEach((name) => {
    images.push(await loadImage(name));
})

not work, but

for (let i = 0; i < names.length; i++) {
    images.push(await loadImage(names[i]));
}

does?

note: loadImage just returns a Promise, giving a loaded Image()
names is a string-list

Gotti92
  • 742
  • 1
  • 6
  • 22

1 Answers1

-1

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);
Matthew Herbst
  • 29,477
  • 23
  • 85
  • 128
  • *"However, that's not the best thing, because you will be running them all synchronously. Really you want to gather the promises and then wait for them all to finish"* i mean, technically, .map is running them synchronously too, it just makes passing the result to .all easier. – Kevin B Nov 28 '18 at 21:25
  • @KevinB that's not true. My code fires them all off synchronously, and then waits for them all to finish in parallel. The `forEach` code above will wait for each one to finish before running the next iteration of the loop. – Matthew Herbst Nov 28 '18 at 21:27
  • 2
    No, forEach will not wait. a for loop would. Both cases in your answer will run all the requests in parallel. – Kevin B Nov 28 '18 at 21:27
  • @KevinB https://stackoverflow.com/questions/37576685/using-async-await-with-a-foreach-loop – Matthew Herbst Nov 28 '18 at 21:29