美文网首页
map,each迭代函数中的async await用法(同时可以

map,each迭代函数中的async await用法(同时可以

作者: sorry510 | 来源:发表于2019-10-25 17:20 被阅读0次
// 定义一个异步函数
const sleep = time=> new Promise(resolve=> setTimeout(()=> resolve('ok'), time))

const arr = [1, 2, 3]
const time = 1000

// 使用Promise.all()接收所有的异步函数处理结果
;(async ()=> {
    console.time('test1')
    console.log(1)
    const arr2 = await Promise.all(arr.map(async item=> await sleep(time)))
    console.log(arr2)
    console.log(2)
    console.timeEnd('test1')
    // 总输出时间是1秒多
})()

;(async ()=> {
    console.time('test2')
    console.log(1)
    const arr3 = []
    for(let i = 0; i < arr.length; i++) {
        arr3.push(await sleep(time))
    }
    console.log(arr3)
    console.log(2)
    console.timeEnd('test2')
    //输出时间是3秒多
})()

相关文章

网友评论

      本文标题:map,each迭代函数中的async await用法(同时可以

      本文链接:https://www.haomeiwen.com/subject/keqevctx.html