【发布时间】:2018-02-06 22:18:11
【问题描述】:
我有一个 for 循环
for (let i = 0; i < options.length; i++) {
console.log("Entered the to for " + i);
let employee = await this.prolesChecker.getEmployeesFromEmail(options[i]);
let isOnVacation = await this.prolesChecker.isOnVacation(employee, moment());
}
“getEmployeesFromEmail 和 isOnVacation”这两个函数正在连接到数据库,它们需要一些时间才能返回结果。 我希望 for 循环等到返回结果后再进行下一次迭代。
例如,console.log 总是打印出来
Entered the to for 0
它永远不会达到 i = 1
这里是函数
public async deleteEmailsTo(options: any) {
console.log(options.length);
for (let i = 0; i < options.length; i++) {
console.log("Entered the to for " + i);
let employee = await this.prolesChecker.getEmployeesFromEmail(options[i]);
let isOnVacation = await this.prolesChecker.isOnVacation(employee, moment());
if ((!employee.EmailReminders && !isOnVacation) || (!employee.EmailReminders && !employee.EmailRemindersForHoliday && isOnVacation)) {
let index = options.indexOf(options[i], 0);
if (index > -1) {
options.splice(index, 1);
console.log("Removed " + employee.Name + " " + employee.LastName + " from the 'to' list");
}
}
}
}
有什么建议吗?
【问题讨论】:
-
如果函数中有for循环?如果是这样,函数必须是
async -
循环已经确实等待返回的promise得到结果。如果它永远等待,这表明返回的 Promise 没有正确解决。给我们看
getEmployeesFromEmail和isOnVacation的相关代码 -
@JulianZucker 是,否则会立即抛出语法错误而不是前进到第一个
console.log -
@Subburaj 不,他不应该。使用
async/await语法的 Promise 远远优于 async.js 模块。 -
我发现错误出现在其他函数“getEmployeesFromEmail”中,该函数正在对选项数组进行“拼接”。
标签: javascript node.js loops asynchronous