I have a async function let say sendEmail
which sends emails to users. My sample code is as follows:
const sampleFunc = (users) => {
for (const user of users) {
// process user obj and get 'to', 'from', 'body'
sendEmail(to, from, body) // this is an async function
}
return // return only when all the emails are sent.
}
What I want is to return ONLY when all the emails are sent. I can easily do it by adding await
before sendEmail
function, but then I loose the asynchronous behaviour where I cannot process then next user
object unless the email is sent for current user.
Is there a way where I can add sendEmail
to something like Promise.all()
array dynamically while those already added instances of sendEmail
are being processed as I m adding.
For example, if there are 10 users in the users
array and currently I'm processing the 5th user
, then the sendEmail
function is already working for the first 5 users and I'm adding users dynamically. Then just before return, I will wait until all the emails are sent for 10 users, and then return.