代码需求
有一个数组,需要依次处理数组里面的每个对象,处理的过程是一个异步操作。想要在所有元素全部处理完再执行接下来的操作。
实现 async/await
// 首先提供一个异步函数sleep方便模拟,作用是帮我们延时xx秒
function sleep(time) {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve()
}, time * 1000)
})
}
const arr = [1, 2, 3, 4, 5]
// for 循环的执行
async function main() {
for (let i = 0; i < arr.length; i++) {
await sleep(1)
console.log(arr[i])
}
console.log('完成')
}
main() // 执行一下
async function main() {
promiseArr = arr.map(async item => {
await sleep(1)
console.log(item)
})
await Promise.all(promiseArr)
console.log('完成')
}
// 或者如果你真的很想用forEach的话
async function main() {
let promiseArr = []
arr.forEach(item => {
promiseArr.push((async (item) => {
await sleep(1)
console.log(item)
})(item))
})
await Promise.all(promiseArr)
console.log('完成')
}
main()
原文地址.
感谢大佬!!!