常用的forEach方法,处理异步函数会有问题,
可以使用map和for方法代替之:
const arr = [3, 2, 4, 1]
console.log('start ' + arr)
// forEach产生的异步问题
async function forEachTest() {
arr.forEach(async item => {
const res = await mockSync(item)
console.log('forEach ' + res)
})
console.log('forEach end')
}
function mockSync(x) {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(x)
}, 1000 * x)
})
}
forEachTest() // 期望输出: 3, 2, 4, 1, end forEach; 实际输出: end forEach, 1, 2, 3, 4
// 替代forEach的方式一:map可以避免异步问题
async function asyncFunction(num) {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(num);
}, 1000);
});
}
const mapTest = arr.map(async (num) => {
const result = await asyncFunction(num);
return result;
});
Promise.all(mapTest).then((results) => {
console.log('map ' + results); // [3, 2, 4, 1]
console.log('map end') // end map
});
// 替代forEach的方式二:使用for循环来处理异步函数
async function forTest() {
for (let i = 0; i < arr.length; i++) {
const result = await asyncFunction(arr[i]);
// results.push(result);
console.log('for ' + result); // 3, 2, 4, 1
}
console.log('for end') // end for
}
forTest();