[英]Node.js wait until each iteration in for loop
我有一個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
永遠不會到我= 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;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.