首页 > 编程语言 > 详细

JavaScript中的for...of

时间:2021-05-08 16:09:19      阅读:20      评论:0      收藏:0      [点我收藏+]

for...in、forEach、for是常规的同步遍历,而for...of是常用于异步的遍历

// 定时算乘法
function multi(num) {
    return new Promise((resolve) => {
        setTimeout(() => {
            resolve(num * num)
        }, 1000)
    })
}

// // 使用 forEach ,是 1s 之后打印出所有结果,即 3 个值是一起被计算出来的
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 会挨个串行计算
        const res = await multi(x)
        console.log(res)
    }
}
test2()

 

JavaScript中的for...of

原文:https://www.cnblogs.com/starlog/p/14745005.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!