zl程序教程

您现在的位置是:首页 >  前端

当前栏目

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

JavaScript for of with Array an use await
2023-09-14 09:00:47 时间

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