作为for循环的增强版,forEach在遍历数组时书写更简洁、可读性也更强。但是当循环中包含异步操作时可能会遇一些坑。下面看看两者异步调用时的一些区别:
promise setTimeOut模拟异步
async function log(info) {
return new Promise((resolve, reject) => {
try {
setTimeout(() => {
resolve(`info is ${info}`)
}, 100)
} catch (err) {
reject (err)
}
})
}
for循环调用异步
async function funFor () {
for (let i = 0; i < 3; i ++) {
const res = await log('for ' + i)
console.log(res)
}
console.log('for is completed...')
}
funFro() // 调用
/*
结果:
info is for 0
info is for 1
info is for 2
for is finish...
*/
forEach调用异步
async function funForEach () {
[1, 2, 3].forEach(async (i) => {
const res = await log('forEach ' + i)
console.log(res)
})
console.log('forEach is completed...')
}
funForEach() // 调用
/*
结果:
forEach is finish...
info is forEach 1
info is forEach 2
info is forEach 3
*/
比较
- for循环中包含异步调用时会等异步调用完成后再执行后面的语句(先输出1、2、3最后输出completed)
- forEach中包含异步调用时会直接执行后面的语句(先输出completed,然后输出1、2、3)
结论
- 如果循环中包含了异步调用、并且循环后的同步操作调用了遍历后的结果,应该使用for循环代替forEach

本文探讨了for循环和forEach在处理异步调用时的不同行为。for循环等待每个异步操作完成,而forEach则立即执行后续代码,可能导致结果顺序混乱。建议在涉及异步操作且依赖结果顺序时使用for循环。

被折叠的 条评论
为什么被折叠?



