Typescript 如何在For循环中返回承诺函数?
我有一个功能(sendEmail),您可以在这里看到: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) => { .
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);
}
}
}