Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Explain Promise.all with async-await in JavaScript?
Simple operations like adding two numbers or string manipulation codes execute sequentially in JavaScript and return the results instantly. But while coding for real-world applications, we frequently make time-taking calls to databases, APIs, and other applications. These longer calls don't return the results instantly; they will rather return a promise.
A promise is an object to represent the future results of an asynchronous operation. It is used to handle asynchronous processes' eventual success or failure. For instance, if you request some object from an API in JavaScript, you will be given a promise that the task will eventually be complete or fail. After some time, you will get the result of the promise, whether it is fulfilled or rejected.
What is Promise.all()?
Promise.all() is a utility method that runs multiple asynchronous operations concurrently and waits for all of them to complete:
Takes an array of promises as input and returns a single promise
If all input promises resolve, returns an array of all resolved values in the same order
If any promise rejects, immediately rejects with the first rejection reason
All promises run concurrently, not sequentially, making it faster than awaiting them one by one
Syntax
Promise.all([promise1, promise2, promise3])
Combining Promise.all() with async-await
The async keyword is used to declare an asynchronous function, and the "await" keyword can be used in the body of that function. When combined with Promise.all(), this provides clean, readable code for handling multiple concurrent operations:
async function example() {
try {
const results = await Promise.all([promise1, promise2, promise3]);
// results is an array containing resolved values
} catch (error) {
// Handle if any promise rejects
}
}
Example 1: All Promises Resolve Successfully
Let's create three promises representing social media actions (like, comment, share) and use Promise.all() with async-await to handle them concurrently:
<html>
<body>
<h3>Using Promise.all() with async-await</h3>
<p id="output1"></p>
<script>
const likePromise = () => {
return new Promise((resolve) => {
setTimeout(() => resolve("Liked"), 1000);
});
};
const commentPromise = () => {
return new Promise((resolve) => {
setTimeout(() => resolve("Commented"), 1500);
});
};
const sharePromise = () => {
return new Promise((resolve) => {
setTimeout(() => resolve("Shared"), 800);
});
};
const handleActions = async () => {
try {
const results = await Promise.all([
likePromise(),
commentPromise(),
sharePromise()
]);
document.getElementById("output1").innerHTML =
"Actions completed: " + results.join(", ");
} catch (error) {
document.getElementById("output1").innerHTML = "Error: " + error;
}
};
handleActions();
</script>
</body>
</html>
Example 2: Handling Promise Rejection
When any promise in Promise.all() rejects, the entire operation fails immediately. Here's an example with blog operations where one promise rejects:
<html>
<body>
<h3>Promise.all() with Rejection Handling</h3>
<p id="output2"></p>
<script>
const postBlog = () => {
return new Promise((resolve) => {
setTimeout(() => resolve("Blog posted successfully"), 1000);
});
};
const saveDraft = () => {
return new Promise((resolve) => {
setTimeout(() => resolve("Draft saved"), 800);
});
};
const deleteBlog = () => {
return new Promise((resolve, reject) => {
setTimeout(() => reject("Permission denied: Cannot delete"), 500);
});
};
const manageBlog = async () => {
try {
const results = await Promise.all([
postBlog(),
saveDraft(),
deleteBlog()
]);
document.getElementById("output2").innerHTML =
"All operations completed: " + results.join(", ");
} catch (error) {
document.getElementById("output2").innerHTML =
"Operation failed: " + error;
}
};
manageBlog();
</script>
</body>
</html>
Key Benefits
| Approach | Execution | Speed | Error Handling |
|---|---|---|---|
| Sequential await | One by one | Slower | Individual control |
| Promise.all() + async-await | Concurrent | Faster | All-or-nothing |
Conclusion
Promise.all() with async-await provides an efficient way to handle multiple asynchronous operations concurrently. It's ideal when you need all operations to succeed, but remember that any single rejection will cause the entire operation to fail.
