猿问

async/await 与 forEach 问题

方法一:没问题

    (async function () {
        for (let i = 0; i < triggerArr.length; ++i) {
            await sleep();
            triggerArr[i]();
        }
    })();

方法二:是一起输出来的,为什么?(没有等待)

    const test = async function (item) {            await sleep();
            item();
    };

    triggerArr.forEach(test);

全部的代码

呼唤远方
浏览 540回答 1
1回答

米琪卡哇伊

我给你讲下。await 只能用于 async 声明的函数上下文中. 如下 forEach 中, 是不能直接使用await的.let array = [0,1,2,3,4,5];(async ()=>{&nbsp; array.forEach(function(item){&nbsp; &nbsp; console.log(item);&nbsp; &nbsp; await wait(1000);//这是错误的写法&nbsp; });})();//因await只能用于 async 声明的函数上下文中, 故不能写在forEach内.下面我们来看正确的写法(async ()=>{&nbsp; for(let i=0,len=array.length;i<len;i++){&nbsp; &nbsp; console.log(array[i]);&nbsp; &nbsp; await wait(1000);&nbsp; }})();仔细看下,发现你的问题是另外一种情况。你这样把test当做回调函数传入进去,sleep方法是同步执行的,await还是生效的,只是同时生效。因此后续函数在等待相同的时间后,一起执行。
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答