JSFiddle - React, Tailwind, and code Playground

by anonystick

JavaScript

let users  = [{
	username: 'anonystick',
  age: 1
},{
	username: 'anonystick',
  age: 2
},{
	username: 'anonystick',
  age: 3
},{
	username: 'anonystick',
  age: 4
},{
	username: 'anonystick',
  age: 5
},{
	username: 'anonystick',
  age: 6
},{
	username: 'anonystick',
  age: 7
},{
	username: 'anonystick',
  age: 8
},{
	username: 'anonystick',
  age: 9
},{
	username: 'anonystick',
  age: 10
}]

// 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 += 2) { 
  	console.log('requests>>', users.slice(i, i + 2))
    const requests = users.slice(i, i + 2).map((user) => { // The batch size is 100. We are processing in a set of 100 users.
      return new Promise((resolve, reject) => {
    		setTimeout(() => {
      		resolve(`Completed in ${user}`)
      	}, 1000)
  		})
      //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.
    })
    
    await Promise.all(requests).then( (result) => {
   		console.log(result)
 		})
 
    // requests will have 100 or less pending promises. 
    // Promise.all will wait till all the promises got resolves and then take the next 100.

  }
}


sendMailForUsers(users)