To wait for all the promises to resolve, you can use the all()
method in the global Promise
object and pass the promises as an array to the method in JavaScript.
TL;DR
// Promises
Promise1 = Promise.resolve("Hello");
Promise2 = Promise.resolve("Hai");
// Resolve when both promises resolve
Promise.all([Promise1, Promise2])
.then((res) => console.log(res))
.catch((err) => console.error(err));
For an example, Consider 2 fetch requests which fetches 2 posts from an api like this,
// 2 fetch requests for 2 posts
const fetch1 = fetch("https://jsonplaceholder.typicode.com/posts/1");
const fetch2 = fetch("https://jsonplaceholder.typicode.com/posts/2");
Now let's use the Promise.all()
method and pass the 2 fetch requests as an array to the method like this,
// 2 fetch requests for 2 posts
const fetch1 = fetch("https://jsonplaceholder.typicode.com/posts/1");
const fetch2 = fetch("https://jsonplaceholder.typicode.com/posts/2");
// Pass both the 2 fetch requests
// as an array to the Promise.all() method
Promise.all([fetch1, fetch2]);
-
The
Promise.all()
method returns another promise which will resolve only if both the fetch requests are resolved. -
If any one of the
Promises
passed to thePromise.all()
method is rejected, the promise will not resolve. So be on the lookout for that.
So now let's add the then()
and catch()
to the Promise.all()
method like this,
// 2 fetch requests for 2 posts
const fetch1 = fetch("https://jsonplaceholder.typicode.com/posts/1");
const fetch2 = fetch("https://jsonplaceholder.typicode.com/posts/2");
// Pass both the 2 fetch requests
// as an array to the Promise.all() method
Promise.all([fetch1, fetch2])
.then((res) => console.log(res))
.catch((err) => console.error(err));
- If all the above fetch Promises are resolved, you will get the response of both the fetch requests as an array in the
Promise.all()
's'then()
handler.
See this example live in JSBin.