demo 如下
const a = [1, 2, 3, 4, 5];
const b = [];
const c = [];
(async () => {
// Promise.all(a.map(async (item) => {
await Promise.all(a.map(async (item) => {
if (item % 2 === 0) {
b.push(item);
}
}));
await Promise.all(a.map(async (item) => {
if (item % 2 === 1) {
c.push(item);
}
}));
})();
console.log('222', b);
console.log('333', c);
输出结果:
- 第一个
Promise.all前添加了await
222 [ 2, 4 ]
333 []
- 第一个
Promise.all前没有添加await
222 [ 2, 4 ]
333 [ 1, 3, 5 ]
我查询了与 Promise.all 和 await 相关的文档,大概觉得应该是与 微任务和宏任务的执行顺序有关,但看了还是觉得一知半解的,希望能得到前辈们的解惑。