One of the ways you can effectively manage multiple promises concurrently in JavaScript is by using Promise.all()
.
Promise.all()
is a method in JavaScript that takes an iterable of promises as input and returns a single promise.
A simple promise looks like this:
const simplePromise = new Promise((resolve, reject) => {
const success = true;
if (success) {
resolve('The operation was successful!');
} else {
reject('The operation failed.');
}
});
If the success condition is true, the promise will resolve; otherwise, it will be rejected.
To consume the promise, you would handle it like this. For example, if you run this in a browser, you can see that the promise has been fulfilled.
Syntax
The syntax for promise.all() method looks like this:
Promise.all(iterable);
Behaviour
If all promises are fulfilled:
Promise.all()
will return a single promise that resolves to an array containing the resolved values of all the promises. Each element in this array corresponds to the result of the promises in the order they were passed toPromise.all()
.If any promise fails:
Promise.all()
will immediately reject with the reason of the first promise that fails. Even if other promises in the iterable have been fulfilled,Promise.all()
will not wait for them to finish and will reject as soon as one of the promises fails.
For example, suppose you need to get the current weather for different cities using the weather API. First, we would define our cities in an array as shown below:
const cities = ['London', 'Hong Kong', 'Johannesburg'];
Next, create a function to fetch the weather for each city:
function fetchWeather(city) {
const url = `https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${APIKEY}`;
return fetch(url)
.then(response => {
if (!response.ok) {
throw new Error(`Failed to fetch weather for ${city}`);
}
return response.json();
});
}
The function fetchWeather
returns a promise that resolves with the weather data in JSON format. The promise will be fulfilled with the weather data or rejected if the request fails.
The next step is to create an array of promises, where each promise corresponds to fetching the weather for a city:
async function fetchAllWeather() {
const weatherPromises = cities.map((city) => fetchWeather(city));
}
Then we will use promise.all() and pass the array of promises. Here is the full code.
When you run the code, you can see that the first output is the promise going to pending, then it is fulfilled with the weather information for the three cities.
If any of the cities doesn't exist, all the promises will be rejected.