js异步循环

let arr = [8, 4, 7]
function timeout(time) {
    return new Promise(function (resolve, reject) {
        setTimeout(function () {
            resolve(time)
        }, time * 1000)
    })
}

1.第一种

async function test(arr) {
    for await (let item of arr) {
        timeout(item).then(res => {
            console.log(res);
        })
    }
}

按延迟的顺序执行4,7,8,总共8s,4s时输出4,7s时输出7,8s时输出8,跟不加async…await没啥区别

2.第二种

function test1(arr) {
    arr.forEach(async item => {
        const res = await timeout(item)
        console.log(res);
    });
}

按延迟的时间长短顺序执行4,7,8,分别延迟4s,7s,8s,总共21s

3.第三种

async function test2(arr) {
    for (let item of arr) {
        const res = await timeout(item)
        console.log(res);
    }
}

按数组的顺序执行 8,4,7,分别延迟8s,4s,7s,总共21s ,所以第三种才是最终想要的方案

1.为什么同样是遍历,输出结果却不一样呢?

因为 for…of 内部处理的机制和 forEach 不同,forEach 是直接调用回调函数,for…of 是通过迭代器的方式去遍历。

// 参考下 Polyfill 版本的 forEach,简化后的伪代码:
while (index < arr.length) {
    callback(item, index)  //我们传入的回调函数
}
async function test3(arr) {
    const iterator = arr[Symbol.iterator]()  //for of会自动调用遍历器函数
    let res = iterator.next()
    while (!res.done) {
        const value = res.value
        const res1 = await timeout(value)
        console.log(res1)
        res = iterator.next()
    }
}
test3(arr)

2.for of是await这一行代码在等待,for await of 是整个for循环在等待

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值