如何在For循环中返回Promise函数?

时间:2017-12-05 14:13:06

标签: typescript for-loop promise

我有一个函数(sendEmail),如你所见:

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

我想在for循环中使用它:

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

我无法删除&#34;返回this.sendEmail(log)&#34;,因为该函数返回Promise。但循环只工作一次,第一次登录时,它将被终止。 如何在此循环中使用该函数?

1 个答案:

答案 0 :(得分:2)

您需要将所有承诺放在一个数组中,并创建一个在所有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 / await在发送下一封邮件之前等待电子邮件:

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