How to wait for multiple Promises in JavaScript ?
Last Updated :
07 Jun, 2024
Waiting for multiple promises in JavaScript involves using Promise.all() or Promise.allSettled() methods. These methods accept an array of promises as input. Promise.all() waits for all promises to either resolve or reject, providing a single promise that resolves with an array of results or rejects with the first rejection. Promise.allSettled() waits for all promises to settle, providing a promise that resolves with an array of objects representing the outcome of each promise.
A Promise is basically an object that represents the completion (or failure) of an asynchronous operation along with its result. A promise has 3 types of states and based upon these states, the promise executes the results.
- Pending: This state represents that the promise is still in progress and hasn't been fulfilled or rejected.
- Fulfilled: This state represents that the asynchronous operation is successfully completed.
- Rejected: This state represents that the asynchronous operation is rejected.
Promise. all( )
Promise. all() in JavaScript handles multiple promises concurrently, resolving when all promises in an array resolve, or rejecting if any of them fail, streamlining asynchronous operations.
Syntax
Promise.all([
// Array of promises
promise1,
promise2,
])
.then((results) => {
// Handle the resolved results
})
.catch((error) => {
// Handle errors on promise rejection.
});
Approach
- Create an array of promises that you want to wait for, e.g. promise1, promise2, and so on.
- Use Promise.all with the array of promises as its argument to wait for all of them to resolve. This method returns a new promise.
- In the .then callback, you can access the resolved values from all the promises as an array called results and handle them as needed.
- In the .catch callback, you can handle errors if at least one of the promises in the array is rejected.
Example: This example illustrates how to wait for multiple promises by using Promise.all( ) function in JavaScript.
JavaScript
// Array of promises
const promises = [
new Promise((resolve) =>
setTimeout(() => resolve("first"), 2000)),
new Promise((resolve) =>
setTimeout(() => resolve("second"), 2500)),
new Promise((resolve) =>
setTimeout(() => resolve("third"), 1000)),
];
// Use Promise.all to wait
// for all promises to resolve
Promise.all(promises)
.then((result) => {
console.log("All promises have been resolved ", result);
// Handle the resolved values here
})
.catch((error) => {
console.error(
"At least any one promise is rejected:", error);
});
Output:
All promises have been resolved [ 'first', 'second', 'third' ]
Async/await
Async/await is a JavaScript feature used to simplify asynchronous programming by allowing code to pause and resume using the await keyword within functions marked as async, enhancing readability and maintainability.
Syntax
async function fetchData() {
const [res1, res2] = await Promise.all([
fetch(' '),
fetch(' '),
]);
// Perform operations on result received
}
fetchData();
Approach
- Start by defining an async function, and create a function to handle your code after all promises are done.
- Inside the async function, create an array of promises, and collect promises for each asynchronous operation you need to await.
- Utilize the Promise.all() method to await all promises.
- After all promises have been resolved, we'll receive an array of results: Once everything is done, you'll get an array of results.
Example: This is the code showing how to wait for multiple promises by using async await in JavaScript.
JavaScript
async function fetchData() {
// Fetching the users profile
// and follower data in parallel
const [title1, title2] =
await Promise.all([
(await fetch('https://...example.com/'))
.json(),
(await fetch('https://...example.com/'))
.json(),
]);
alert(`First title is
${title1.title} and Second title is
${title2.title}`);
}
fetchData();
Output:
OutputNote: For this example, you may use any random Public API for the desired output.
Similar Reads
How to Execute Multiple Promises Sequentially in JavaScript?
In JavaScript, executing multiple promises sequentially refers to running asynchronous tasks in a specific order, ensuring each task is completed before the next begins. This is essential when tasks depend on the results of previous ones, ensuring correct flow and preventing unexpected behavior.Foll
4 min read
How to Wait n Seconds in JavaScript?
Here are the various methods to wait n seconds in JavaScript1. Using setTimeout() FunctionsetTimeout() is an asynchronous function in JavaScript that allows you to run code after a specific amount of time has passed. Since setTimeout() is a method of the window object, you can technically write it a
3 min read
How to set the cursor to wait in JavaScript ?
In JavaScript, we could easily set the cursor to wait. In this article, we will see how we are going to do this. Actually, it's quite an easy task, there is a CSS cursor property and it has some values and one of the values is wait. We will use the [cursor: wait] property of CSS and control its beha
3 min read
How to use Native JavaScript Promises in Postman ?
Postman is a popular tool used by developers for testing APIs. While Postman primarily offers a graphical user interface (GUI) for making HTTP requests, it also supports scripting capabilities using JavaScript. One common use case for scripting in Postman is making asynchronous requests and handling
3 min read
How to Make JavaScript Sleep or Wait?
In JavaScript, there is no built-in sleep function like in some other programming languages. However, you can create a delay or pause in code execution by using asynchronous methods.We can use setTimeout() or Promise along with async/await to achieve this functionality for more readable code.1. Usin
2 min read
How to Convert Callback to Promise in JavaScript ?
Asynchronous programming in JavaScript often involves the use of callbacks. However, callbacks can lead to callback hell and make the code harder to read and maintain. Promises provide a cleaner way to handle asynchronous operations. Converting existing callback-based code to use promises can improv
2 min read
How to call promise inside another promise in JavaScript ?
In JavaScript, to call promise inside another promise we first declare a promise using its basic syntax and further execute this promise then create another which is to be called inside the previous promise for its execution. Promise is basically a JavaScript object which is responsible for handling
3 min read
JavaScript - How to Handle Errors in Promise.all?
To handle errors in Promise.all(), you need to understand that it fails immediately if any of the promises reject, discarding all resolved values. This behavior can lead to incomplete operations and potential application crashes. The best way to manage errors in Promise.all() is by using .catch() in
3 min read
How to use every() or some() methods in JavaScript ?
In JavaScript, the every() and some() methods are array methods used to check the elements of an array based on a given condition. every(): Checks if all elements in an array satisfy a condition.some(): Checks if at least one element in an array satisfies a condition.Table of Content every() Methods
2 min read
How to access the Value of a Promise in JavaScript
In this article, we will see how to access the value of Promise in JavaScript. The Promise is a feature of ES6 introduced in 2015. The concept of Promises is generally used when we want to work asynchronously. The value of a Promise can be accessed in JavaScript using the following methods. Table of
2 min read