如何在循环中返回承诺功能



我有一个函数(sendemail),如您所在:

public async sendEmail (log: LogMessage): Promise<void> {
nodemailer.createTestAccount(async () => {
      return ServiceFactory.getSystemService().getNetworkPreferences().then(async (networkPreferences) => {
....

我想在循环中使用它:

for (const log of logs) {
          const timestamp = moment(log.creationDate)
          const startTime = new Date(Date.now())
          if ((timestamp.diff(startTime)) >= rule.miliSecond && category.includes(log.category)) {
            return this.sendEmail(log)
          }
        }

我无法删除"返回this.sendemail(log)",因为该函数返回承诺。但是循环只能工作一次,并且使用第一个日志,它将被终止。如何在此循环中使用该函数?

您需要将所有承诺放在数组中,并在所有sendEmail承诺完成时创建一个诺言。

sendAll() {
    let allMails: Promise<void>[] = [];
    for (const log of logs) {
        const timestamp = moment(log.creationDate)
        const startTime = new Date(Date.now())
        if ((timestamp.diff(startTime)) >= rule.miliSecond && category.includes(log.category)) {
            allMails.push(this.sendEmail(log));
        }
    }
    return Promise.all(allMails);
}

以上版本并行启动所有请求。如果要顺序运行sendEmail,则可以使用Async/等待在发送下一封电子邮件之前等待:

async sendAll() : Promise<void>{
    for (const log of logs) {
        const timestamp = moment(log.creationDate)
        const startTime = new Date(Date.now())
        if ((timestamp.diff(startTime)) >= rule.miliSecond && category.includes(log.category)) {
            await this.sendEmail(log);
        }
    }
}

最新更新