• js中的for await of有用过吗?
  • 发布于 2个月前
  • 331 热度
    0 评论
先来看一个场景,假如有一个promise方法。
const getResult = () => {
    return new Promise(resolve => {
        setTimeout(() => {
            resolve("后台返回的数据")
        },1000)
    });
}

(async function(){
    let result =  getResult();
    let result1 = getResult();
    let result2 = getResult();
    Promise.all([result,result1,result2]).then(res => {
        console.log(res)
    })

})();
注意,我们直接调用的 getResult方法三次,他们是同时执行的,然后再用 Promise.all 聚合起来,最后打印,这个过程是在1秒钟内发生的。
注意,这种写法最终拿到的还是一个数组。

众所周知,当你把鸡和篮球联系起来,会有意想不到的结果。同理,当你把for of 和 await 结合起来,会怎么样呢。
for await (let value of [result,result1,result2]) {
    console.log(value)
}
这就是三个promise同时执行,最后一起返回,可以说是Promise.all的优雅平替。而且,这种写法本质还是for of,所以你需要用同样的逻辑去处理每一个value即可,不需要再对Promise.all拿到的结果数组进行遍历了。

总结
for await of 就是Promise.all的替代品,但Promise.all是API,用起来有点麻烦,而for await of则是语法层面的原生操作,用来遍历多个异步处理的结果非常合适。
用户评论