我有一个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");
}
}
}
}
请问有什么建议吗?
最佳答案
您的问题实际上与 async
/await
语法无关,该语法工作正常。这是关于迭代过程中splice
的使用!这会更改数组的 .length
,并且下一次迭代不会发生,因为循环条件不再适用。
如果您绝对必须更改传递的数组,请递减 index
计数器以考虑长度的变化:
for (let i = 0; i < options.length; i++) {
…
if (…) {
let index = i; // no point in using `options.indexOf(options[i], 0);`
// if (index > -1) { always true
options.splice(index--, 1);
// ^^^^^^^
}
}
但是简单地创建一个新数组可能要容易得多:
let result = [];
for (let i = 0; i < options.length; i++) {
…
if (!…) {
result.push(options[i]);
}
}
return result;
关于javascript - Node.js 等待 for 循环中的每次迭代,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45939428/