Rather than using any of the for
methods, to await multiple items, you can use
the Promise.all()
method. It is good practice to think of the types of the
data you are working with. As can be seen below, Promise.all converts an array
of promises into a single promise.
Promise.all(promises: Promise[]): Promise;
Let's say that we have an array of URLs that we want to fetch.
const urls = [
"https://jsonplaceholder.typicode.com/users",
"https://jsonplaceholder.typicode.com/posts",
"https://jsonplaceholder.typicode.com/albums",
];
We can use the .map()
method to convert this array of strings to an array of
promises.
const promises = urls.map((url) => {
return fetch(url);
});
Now that we have an array of promises, we can use Promise.all() to convert it into a single promise.
const resultsPromise = Promise.all(requests);
A single promise can be awaited using the await
keyword, or using .then()
.
const results = await Promise.all(requests);
console.log(results);
Promise.all(requests).then((results) => {
console.log(results);
});
It it important to note that the promise returned from Promise.all() will only resolve when all of the promises passed into Promise.all() have resolved.
Furthermore, if any of the promises passed into Promise.all() are rejected, the promise returned from the Promise.all() method will be rejected.
In case a different behavior is desired, the Promise.allSettled()
method can
be used. It will return a promise that will resolve when all of the promises
passed into it have resolved or rejected.
Also see: Promise.all() and Promise.allSettled() on MDN.