我可以使用JavaScript使用forEach实现异步等待吗?

时间:2020-05-20 13:44:08

标签: javascript node.js google-cloud-functions

我有一系列对象,其中有电子邮件和用户信息,我想使用AWS SES发送电子邮件,并且要发送电子邮件,我必须添加await或normal。然后才能发送消息,但我想使用await是否可以在forEach

中使用await

此处userRecord为[{},{},{}]

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);
            }
      }
    });

2 个答案:

答案 0 :(得分:2)

async/await来实现forEach会很困难,但是使用map()会很容易,因为map()返回了一系列我们可以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);

答案 1 :(得分:0)

将promise放在一个数组上,然后立即解决它。

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
});