【发布时间】:2021-07-29 20:01:15
【问题描述】:
假设我有这个代码:
const array = [1, 2, 3]
let counter = 0
array.map(async (item) => {
console.log(await item, ++counter)
console.log(await item, ++counter)
})
预期的输出是
1, 1
1, 2
2, 3
2, 4
3, 5
3, 6
但我得到的是这个
1, 1
2, 2
3, 3
1, 4
2, 5
3, 6
似乎第一个 await 调用首先针对整个阵列运行,然后第二个正在运行,为什么会发生这种情况?
【问题讨论】:
-
你为什么期待初始输出?
-
你为什么需要
await一个号码? -
这只是简化@Pointy的更大问题的一部分
-
异步函数在
await处暂停。这就是关于你的问题的全部解释。但是解决你的问题真的有用吗?您很可能不应该在.map()中使用异步。除非你把它放在Promise.all() -
@Keith,谢谢你,我一定会读到的。
标签: javascript node.js arrays async-await promise