[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

猜你喜欢

转载自www.cnblogs.com/Answer1215/p/12543891.html