准备代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
const res = [] const arr = [1, 2, 3, 4, 5] function t(num) { return new Promise((resolve, reject) => { setTimeout(() => { console.log('定时器', num) resolve() }, 1000) }) } function t2(item) { console.log('进入res') res.push(item) } |
1 2 3 4 |
arr.forEach(async (item, index) => { await t(item) t2(item) }) |
结果:
1 2 3 4 5 6 7 8 9 |
let asyncFun = [] arr.forEach((item, index) => { asyncFun.push(t(item)) t2(item) }) Promise.all(asyncFun).then(() => { console.log('res', res) }) |
结果:
1 2 3 4 5 6 7 8 9 10 11 12 |
Promise.all( arr.map(item => { return new Promise(async (resolve, reject) => { await t(item) t2(item) resolve() }) }) ).then(() => { console.log('object', res) }) |
结果:
1 2 3 4 5 6 7 |
arr.forEach(async (item, index) => { await t(item) t2(item) if (index === arr.length - 1) { console.log('res', res) } }) |
结果:
from:https://blog.csdn.net/alex_programmer/article/details/104383843