0

I have an array of objects and in that i have emails and user information and i wanted to send emails using AWS SES.and to sending the email i have to add await or normal .then to send the message but i wanted to use await is it possible to use await inside forEach

here userRecord is [{},{},{}]

const userRecord = await Promise.all(recipient.map(getAuth));
    userRecord.forEach(data => {
      if (data.email !== '' && data.email !== undefined) {
        console.log('created');
 try {
              const sendEmail = await SES.sendRawEmail(params).promise();

              console.log('email submitted to SES', sendEmail);
            } catch (error) {
              console.log('error');
              console.error(error);
            }
      }
    });
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
xanderUtin
  • 25
  • 5

2 Answers2

2

It would be difficult to implement async/await with forEach, but it would be easy with map() because map() returns an array of promises we can Promise.all()

const userRecord = await Promise.all(recipient.map(getAuth));
const promises = userRecord.map(async data => {
  if (data.email !== '' && data.email !== undefined) {
    console.log('created');
    try {
      const sendEmail = await SES.sendRawEmail(params).promise();
      console.log('email submitted to SES', sendEmail);
    } catch (error) {
      console.log('error');
      console.error(error);
    }
  }
});
await Promise.all(promises);
zishone
  • 1,196
  • 1
  • 9
  • 11
0

Put the promises on an array, then resolve it at once.

const userRecord = await Promise.all(recipient.map(getAuth));
const sentEmails = [];
userRecord.forEach(data => {
  if (data.email !== '' && data.email !== undefined) {
      console.log('created');
        try {
          sentEmails.push[SES.sendRawEmail(params).promise()];
          console.log('email submitted to SES', sendEmail);
        } catch (error) {
          console.log('error');
          console.error(error);
        }
  }
});

Promise.all(sentEmails).then(arrayOfResults => {
  // next step
});

Mon
  • 39
  • 1