DavidS
DavidS

Reputation: 13

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?

Upvotes: 0

Views: 223

Answers (1)

Bergi
Bergi

Reputation: 664206

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;

Upvotes: 1

Related Questions