Skip to content

Instantly share code, notes, and snippets.

@srebalaji
Last active April 11, 2019 05:07
Show Gist options
  • Save srebalaji/8b3ad7f068ff9771b98d903506649b19 to your computer and use it in GitHub Desktop.
Save srebalaji/8b3ad7f068ff9771b98d903506649b19 to your computer and use it in GitHub Desktop.
A simple Promise all example to send emails
// Async function to send mail to a list of users.
const sendMailForUsers = async (users) => {
const usersLength = users.length
for (let i = 0; i < usersLength; i += 100) {
const requests = users.slice(i, i + 100).map((user) => { // The batch size is 100. We are processing in a set of 100 users.
return triggerMailForUser(user) // Async function to send the mail.
.catch(e => console.log(`Error in sending email for ${user} - ${e}`)) // Catch the error if something goes wrong. So that it won't block the loop.
})
// requests will have 100 or less pending promises.
// Promise.all will wait till all the promises got resolves and then take the next 100.
await Promise.all(requests)
.catch(e => console.log(`Error in sending email for the batch ${i} - ${e}`)) // Catch the error.
}
}
sendMailForUsers(userLists)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment