异步循环
let promiseTasek = (num) => {
return new Promise((resolve, reject) => {
setTimeout(() => {
console.log(num);
resolve(true);
}, 4000);
});
};
async function toTaskByForEach() {
const arr = [1, 2, 3, 4, 5, 6];
arr.forEach(async (item) => {
await promiseTasek(item);
});
}
async function toTaskByForOf() {
const arr = [1, 2, 3, 4, 5, 6];
for (let i of arr) {
await promiseTasek(i);
}
}
toTaskByForEach();//四秒后一起输出,map,some都是这样,因为array.prototype.forEach()本身就不支持异步,即使在callBack里用async修饰也不行
toTaskByForOf();//每隔四秒输出一次 for。。。of,for本身就是迭代器支持异步循环
//for...in 输出的是索引不是值