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

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

posted @ 2020-03-22 02:55  Zhentiw  阅读(103)  评论(0编辑  收藏  举报