Say you need to fire up 2 or more promises and wait for their result.
假设您需要启动2个或更多的Promise并等待其结果。
And you want to go on, once you have both resolved.
双方都解决后,您就想继续。
How can you do so, in JavaScript?
如何使用JavaScript?
You use Promise.all()
:
您使用Promise.all()
:
const promise1 = //...
const promise2 = //...
const data = await Promise.all([promise1, promise2])
const dataFromPromise1 = data[0]
const dataFromPromise2 = data[1]
If you prefer using pure promises and not async/await, use this syntax:
如果您更喜欢使用纯承诺而不是async / await ,请使用以下语法:
const promise1 = //...
const promise2 = //...
Promise.all([promise1, promise2]).then(data => {
const dataFromPromise1 = data[0]
const dataFromPromise2 = data[1]
})
翻译自: https://flaviocopes.com/how-to-wait-multiple-promises-javascript/