[Javascript] Use an Array of Promises with a For Await Of Loop

妖精的绣舞 提交于 2020-03-22 03:55:34

The "for await of" loop syntax enables you to loop through an Array of Promises and await each of the responses asynchronously. This lesson walks you through creating the array and awaiting each of the results.

 

let promises = [
    Promise.resolve(1),
    Promise.resolve(2),
    new Promise(resolve => {
        setTimeout(() => {
            resolve(3)
        }, 3000)
    })
]

async function start() {
    for await (let promise of promises) {
        console.log(promise)
    }
}

start()

 

It will log out

1

2

At once..

 

Then after 3 seconds, log 

3

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!