/

How to Wait for 2 or More Promises to Resolve in JavaScript

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
2
3
4
5
6
7
const promise1 = //...
const promise2 = //...

const data = await Promise.all([promise1, promise2]);

const dataFromPromise1 = data[0];
const dataFromPromise2 = data[1];

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
2
3
4
5
6
7
const promise1 = //...
const promise2 = //...

Promise.all([promise1, promise2]).then(data => {
const dataFromPromise1 = data[0];
const dataFromPromise2 = data[1];
});

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