lodash - _.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 中的调试器会按以下顺序发生:
- 该行
const result = await calc.calculateProductScore(product);
执行了 3 次 - if 语句(返回
boo
,因为没有任何东西被推送到listOfResults
数组中) - 该行
const response = await mutateDB.sendProductScoreData(result.productId, result);
执行了 3 次 - 该行
await listOfResults.push(response);
执行了 3 次
我可以在 lodash forEach 文档https://lodash.com/docs/4.17.15#forEach中看到它提到“不能保证迭代顺序” - 我不应该对这种类型的代码块使用 lodash 吗?如何使用 Lodash 并保证代码执行顺序?
解决方案
我知道如果我想保持事情井井有条,我需要使用for (const product of listOfProducts)
循环......
推荐阅读
- sql - 获取同一张表中的相关列
- python - output_field 存在本地版本但网站上不存在,python 和 django 版本相同
- python - 为什么“扩展”切片在 Python 中不起作用?
- python-3.x - 如何在 Python 中计算可能的最长连续遍历
- c++ - 使用 Nsight Systems 跟踪自定义 CUDA 内核
- angular - ngx-owl-carousel-o 选项自动播放真的不起作用?
- python - 如何从python中的csv制作列表?
- javascript - 构建 JavaScript 画布动画框架
- microsoft-graph-api - microsoft graph 获取可用于获取用户日历的访问令牌
- node.js - 我如何使用节点 js 创建具有到期日期的 tinyURL