Introduction
In Asynchronous JavaScript, Promise
plays a vital role. If you're unfamiliar with asynchronous programming in JavaScript, you can Read about it here. In this article, I'll talk about Promise
, handling multiple promises, and, more specifically, various Promise Methods
and how and when to use them.
Table of Contents:
- What is Promise
- Promise Methods
- Conclusion
Promise
Let's have an overview of Promise
first. In JavaScript, Promise
is used to perform asynchronous operations. It's an object that contains a status & represents the eventual completion (or failure) of an asynchronous operation and its resulting value.
For example, uploading an image to the server is an asynchronous operation. When the image upload process is done, it can return a value or throw an exception error.
The following code is an example of using a Promise
based function.
- A
Promise
has three states:- Pending(⏳): The initial state, where the promise is neither resolved nor rejected
- Fulfilled(✔): The state when the promise is successfully resolved with a value.
- Rejected(❌): The state when the promise fails due to an error or exception.
Understanding .then()
, .catch()
, and .finally()
in Promises
The
.then(
) method is used to handle the result of a fulfilled promise. It executes only when the promise is successfully resolved.The
.catch()
method handles errors when a promise is rejected. It executes if the promise is rejected or if an error occurs in the preceding.then()
block.Both
.then()
and.catch()
always return promises, allowing us to chain promise methods unconditionally to fulfil our requirements.The
.finally()
method is always executed, regardless of whether the promise is fulfilled or rejected. It is commonly used for cleanup tasks, such as hiding a loading spinner or logging completion.
For a more detailed explanation of Promise
Read this awesome article
How to handle multiple promises.
When working with multiple promises, we can use the following methods to handle them as per our requirements.
Promise.all()
Promise.any()
Promise.race()
Promise.allSettled()
All of these methods take zero or more promises (you can say Arrays of Promises) and iterate over them to produce a single Promise. However, each method has its own characteristics.
Let's see how these methods work.
Promise.all()
- Fulfilled if all the promises are resolved.
- returns an array of fulfilled values of Promises.
- Example Code:
- Rejected if at least one Promise is rejected.
- returns the value of the rejected Promise
- Example Code:
- Diagram:
- Use case: When you need all promises to succeed before proceeding (e.g., fetching multiple resources).
Promise.allSettled()
- Fulfills when all promises settle. Does not stop even if there are failed promises.
- returns returns each fulfilled promise as an object.
- if the promise is resolved, it will return the promise value with status.
{
status: 'fulfilled',
value:'result'
}
- if the promise is rejected, it will return the promise rejection reason with status.
{
status: 'rejected',
reason: 'Something went wrong'
}
- Example code:
- Diagram:
- Use case: When you want to handle both successes and failures without stopping the process (e.g., uploading multiple files).
Promise.any()
-
Fulfills when the first promise is resolved.
- returns the value of the first fulfilled promise.
- Example Code:
-
If all promises are rejected, then it will return the rejected Promise with an instance of
AggregateError
which contains all rejection values.- Example Code:
- Example Code:
Use case: When you need the first successful outcome among multiple options (e.g., using redundant APIs or payment gateways, ignoring failures as only need one to succeed).
Promise.race()
- Fulfills if any of the promises are resolved or rejected. It does not matter if the settled promise is resolved or rejected, it returns the promise value of the very first settled Promise.
- Example Code:
- Diagram:
- Use case: When you need to act on the first settled promise, regardless of success or failure (e.g., implementing timeouts).
Conclusion
Promises are a cornerstone of modern JavaScript, enabling efficient handling of asynchronous operations. By mastering methods like Promise.all(), Promise.allSettled(), Promise.any(), and Promise.race(), you can tackle complex workflows with ease. From fetching multiple resources to implementing timeouts, these tools empower you to build robust and scalable applications.
That's all for today. Thank you for reading, and don't forget to connect on LinkedIn or X to get more contents.
If you have any questions or feedback, please leave a comment.
Top comments (0)