for...of
for…of
- for…in(以及forEach for)是常规的同步遍历
- for…of常用于异步的遍历
// 定时算乘法
function multi(num) {
return new Promise((resolve) => {
setTimeout(() => {
resolve(num * num)
}, 1000)
})
}
// // 使用 forEach ,是 1s 之后打印出所有结果,即 3 个值(1 4 9)是一起被计算出来的,不会等待。同时进入Promise
// function test1 () {
// const nums = [1, 2, 3];
// nums.forEach(async x => {
// const res = await multi(x);
// console.log(res);
// })
// }
// test1();
// 使用 for...of ,可以让计算挨个串行执行
async function test2 () {
const nums = [1, 2, 3];
for (let x of nums) {
// 在 for...of 循环体的内部,遇到 await 会挨个串行计算 等第一个await出来,再循环一个进去
const res = await multi(x)
console.log(res)
}
}
test2()