Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Typescript 如何在For循环中返回承诺函数?_Typescript_For Loop_Promise - Fatal编程技术网

Typescript 如何在For循环中返回承诺函数?

Typescript 如何在For循环中返回承诺函数?,typescript,for-loop,promise,Typescript,For Loop,Promise,我有一个功能(sendEmail),您可以在这里看到: public async sendEmail (log: LogMessage): Promise<void> { nodemailer.createTestAccount(async () => { return ServiceFactory.getSystemService().getNetworkPreferences().then(async (networkPreferences) => { .

我有一个功能(sendEmail),您可以在这里看到:

public async sendEmail (log: LogMessage): Promise<void> {
nodemailer.createTestAccount(async () => {
      return ServiceFactory.getSystemService().getNetworkPreferences().then(async (networkPreferences) => {
....
我无法删除“returnthis.sendmail(log)”,因为该函数返回承诺。但是循环只工作一次,在第一个日志中,它将被终止。
如何使用此循环中的函数?

您需要将所有承诺放入一个数组中,并创建一个承诺,该承诺在所有
发送电子邮件
承诺完成时完成

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

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

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

我很确定你应该为nodemailer.createTestAccount和wait做出承诺。不要将
异步函数
作为回调传递。我很确定您应该为
nodeEmailer.createTestAccount
等待
做出承诺。不要将
异步函数作为回调传递。
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);
        }
    }
}