How to Wait for 2 or More Promises to Resolve in JavaScript
If you need to fire up and wait for the result of multiple promises in JavaScript, there is a simple way to do so using Promise.all()
.
Here’s how you can achieve this using async/await
:
1 | const promise1 = //... |
In the example above, promise1
and promise2
represent the promises you want to wait for. Promise.all()
takes an array of promises and returns a new promise that resolves when all the promises in the array have resolved. By using await
, you can wait for Promise.all()
to resolve and then access the data from each individual promise.
If you prefer using pure promises without async/await
, you can use the following syntax:
1 | const promise1 = //... |
In this case, Promise.all()
returns a promise that will resolve with an array of fulfilled values once all the promises are resolved. The then()
method is used to access the resolved data from each promise.
Tags: JavaScript, promises, async/await