【问题标题】:Node.js wait until each iteration in for loopNode.js 等到 for 循环中的每次迭代
【发布时间】: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 没有正确解决。给我们看getEmployeesFromEmailisOnVacation的相关代码
  • @JulianZucker 是,否则会立即抛出语法错误而不是前进到第一个console.log
  • @Subburaj 不,他不应该。使用 async/await 语法的 Promise 远远优于 async.js 模块。
  • 我发现错误出现在其他函数“getEmployeesFromEmail”中,该函数正在对选项数组进行“拼接”。

标签: javascript node.js loops asynchronous


【解决方案1】:

您的问题实际上与 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;

【讨论】:

  • @DavidS 你可能想要accept 然后
猜你喜欢
  • 2018-02-13
  • 1970-01-01
  • 1970-01-01
  • 2020-08-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-06-29
相关资源
最近更新 更多