0

I have an array of emails

emails.forEach(email => sendEmail(email)); --> 1

function2();

sendEmail is an asynchronous function I want function2 to be invoked only after line 1 gets completed

How can I achieve this?

Nithin_phil
  • 101
  • 5
  • `Promise.all(emails.map(email => sendEmail|(email)).then(() => { function2() });` – Roberto Zvjerković Mar 04 '21 at 14:17
  • 1
    Does this answer your question? [Using async/await with a forEach loop](https://stackoverflow.com/questions/37576685/using-async-await-with-a-foreach-loop) – Ivar Mar 04 '21 at 14:19

1 Answers1

0

How can I achieve this?

Don't use forEach. Either use a normal for loop, and await each call, or if you want to run them in parallel use map and await Promise.all.

My preference would be:

async function sendAllEmails(emails) {
    await Promise.all(emails.map(email => sendEmail(email)));
    function2();
}
Jamiec
  • 133,658
  • 13
  • 134
  • 193