首页 > 解决方案 > _.forEach 乱序

问题描述

我在异步函数中有一些代码:

    let listOfResults = [];
    _.forEach(listOfProducts, async function (product) {
      const result = await calc.calculateProductScore(product);
      const response = await mutateDB.sendProductScoreData(result.productId, result);
      await listOfResults.push(response);
    })
    if (listOfResults.length >= 1) {
      return "yay";
    } else {
      return "boo";
    }

鉴于 listOfProducts 数组中有三个项目,当它执行时,单步执行 VS Code 中的调试器会按以下顺序发生:

  1. 该行const result = await calc.calculateProductScore(product);执行了 3 次
  2. if 语句(返回boo,因为没有任何东西被推送到listOfResults数组中)
  3. 该行const response = await mutateDB.sendProductScoreData(result.productId, result);执行了 3 次
  4. 该行await listOfResults.push(response);执行了 3 次

我可以在 lodash forEach 文档https://lodash.com/docs/4.17.15#forEach中看到它提到“不能保证迭代顺序” - 我不应该对这种类型的代码块使用 lodash 吗?如何使用 Lodash 并保证代码执行顺序?

标签: lodash

解决方案


我知道如果我想保持事情井井有条,我需要使用for (const product of listOfProducts)循环......


推荐阅读