简体   繁体   中英

Node.js wait until each iteration in for loop

I have a for loop

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

The two functions "getEmployeesFromEmail and isOnVacation" are connecting to a database and they need some time until result is returned. I want the for loop to wait until the result is returned and then go in the next iteration.

As an example the console.log always prints

Entered the to for 0

It never goes to i = 1

Here is the function

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

Any suggestions please?

Your problem is actually not about the async / await syntax, which works fine. It's about the use of splice during the iteration! That changes the .length of your array, and the next iteration won't happen simply because the loop condition didn't apply any more.

If you absolutely have to mutate the passed array, decrement the index counter to account for the change in length:

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

But it's probably much easier to simply create a new array:

let result = [];
for (let i = 0; i < options.length; i++) {
    …
    if (!…) {
        result.push(options[i]);
    }
}
return result;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM