Array.prototype.forEach
forEach方法对数组的每个元素执行一次提供的函数。 语法: arr.forEach(callback[, thisArg]);
参数:
- callback(currentValue, index?, array?) 问好表示可选
- thisArg可选参数。当执行回调函数时用作 this 的值(参考对象)。
关于异步
forEach是并行的对每个元素执行函数。所以await不会阻碍循环和代码的执行
const arr = [1, 2, 3]
async function wait (time) {
const now = Date.now()
return new Promise((res, rej) => {
setTimeout(() => {
console.log('我是异步执行的函数')
res()
}, time)
})
}
arr.forEach(async (item) => {
await wait(1000)
console.log(item)
return item * 2
})
console.log(arr)
复制代码
打印结果为:
console.log(arr)
,大约1秒后会执行完异步函数,然后执行对应的console.log(item).这里的执行顺序和浏览器的event loop机制相关。 如果想要确保异步代码执行完成后再继续执行,可以使用Promise.all。上面的代码可以改写成:
const arr = [1, 2, 3]
async function wait (time) {
const now = Date.now()
return new Promise((res, rej) => {
se