【转】js中forEach回调同异步问题

转载地址:https://blog.csdn.net/weixin_33933118/article/details/88614376

js中forEach本身是同步的
举个栗子:

[many, too many, so many].forEach((value) => {
    some code;  //  这是一个大数值运算(非异步代码),需要几毫秒的时间
});
other code;  // 这些代码将会阻塞,等到forEach循环完之后执行

这是回调中没有异步代码的情况。

再举一个有异步的

[1, 2, 3].forEach((value) => {
    setTimeout(function() {
        some code;
    }, 1000);
});
other code; // 这部分代码不会被setTimeout阻塞,forEach遍历完1,2,3之后就执行
 
[1, 2, 3].forEach( async (value) => {
    let foo = await promiseFn();
});
other code; // 同样不会受到异步阻塞

上面是2种异步代码形式, 但是都不会阻塞后面的代码。我理解的是:forEach的回调函数会被立即执行,回调里有异步代码,根据EventLoop机制放入调用栈,继续执行同步代码以结束; 回调本身就是异步函数,放入调用栈,结束本次遍历。

结合代码理解:

Array.prototype.forEach = function (callback) {
    for(let index = 0; index < this.length; index++) {
        callback(this[index], index, this);
    }
}

对于常规for循环

const sleep = (timer) => {
    return new Promise((resolve, reject) => {
        setTimeout(resolve, timer);
    });
}
 
const foo = async () => {
    for (let i = 0; i < 5; i++) {
        await sleep(1000);
        console.log(i);
    }
}
 
foo(); // 从1到5,每隔一秒输出一个数字

猜你喜欢

转载自blog.csdn.net/mao_mao37/article/details/105633748