方法一:没问题 (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);全部的代码
1 回答
米琪卡哇伊
TA贡献1998条经验 获得超6个赞
我给你讲下。
await 只能用于 async 声明的函数上下文中. 如下 forEach 中, 是不能直接使用await的.
let array = [0,1,2,3,4,5];
(async ()=>{
array.forEach(function(item){
console.log(item);
await wait(1000);//这是错误的写法
});
})();
//因await只能用于 async 声明的函数上下文中, 故不能写在forEach内.下面我们来看正确的写法
(async ()=>{
for(let i=0,len=array.length;i<len;i++){
console.log(array[i]);
await wait(1000);
}
})();
仔细看下,发现你的问题是另外一种情况。
你这样把test当做回调函数传入进去,sleep方法是同步执行的,await还是生效的,只是同时生效。因此后续函数在等待相同的时间后,一起执行。
添加回答
举报
0/150
提交
取消
