When working with asynchronous operations in JavaScript, Promises provide a robust way to handle multiple asynchronous tasks efficiently. Before diving into async/await, it's essential to understand some core Promise methods:
- Promise.all()
- Promise.any()
- Promise.race()
- Promise.finally()
Let's explore each method in detail with examples.
- ## Promise.all()
The Promise.all() method accepts an iterable (e.g., an array of promises) and returns a single promise that resolves to an array containing results of all input promises.
Key Characteristics:
Resolves only when all promises in the array are fulfilled.
Rejects immediately if any promise in the array is rejected.
Useful when executing multiple asynchronous operations that must complete before proceeding.
const promise1 = new Promise((resolve) => setTimeout(resolve, 300, "resolved1"));
const promise2 = 93; // Non-promise value
const promise3 = new Promise((resolve) => setTimeout(resolve, 100, "resolved2"));
Promise.all([promise1, promise2, promise3])
.then((values) => console.log(values))
.catch((error) => console.log(error));
// Expected output: [ 'resolved1', 93, 'resolved2' ]
## Rejection Behavior:
## If any promise in the array rejects, Promise.all() immediately rejects with that error.
const p1 = new Promise((resolve) => setTimeout(resolve, 1000, "one"));
const p2 = new Promise((resolve) => setTimeout(resolve, 2000, "two"));
const p3 = new Promise((_, reject) => setTimeout(reject, 3000, "rejected"));
Promise.all([p1, p2, p3])
.then((values) => console.log(values))
.catch((error) => console.log(error));
// Expected output: "rejected"
- Promise.any()
The Promise.any() method takes an iterable of promises and returns the first fulfilled promise. If none of the promises resolve, it rejects with an AggregateError.
Key Characteristics:
Resolves as soon as one promise fulfills.
If all promises reject, it returns an AggregateError.
const fastPromise = new Promise((resolve) => setTimeout(resolve, 100, "Done quickly"));
const slowPromise = new Promise((resolve) => setTimeout(resolve, 500, "Done slowly"));
const rejectedPromise = new Promise((_, reject) => setTimeout(reject, 100, "Rejected"));
Promise.any([fastPromise, slowPromise, rejectedPromise])
.then((value) => console.log(value))
.catch((err) => console.log(err));
// Expected output: "Done quickly"
// This is when Promise.any() throws a rejection error.
const rejected = new Promise((_, reject) => setTimeout(reject, 100, "Rejected"));
Promise.any([rejected])
.catch((err) => console.log(err));
// Expected output: "AggregateError: No Promise in Promise.any was resolved"
- Promise.finally()
The finally() method executes a callback regardless of promise resolution or rejection. It is useful for cleanup operations.
Key Characteristics:
Runs the provided callback function regardless of whether the promise resolves or rejects.
Does not modify the resolved or rejected value.
Useful for tasks like closing a loader, resetting states, or releasing resources.
const addNumbers = (a, b) => new Promise((resolve, reject) => {
if (typeof a === "number" && typeof b === "number") {
resolve(a + b);
} else {
reject("Not a Number");
}
});
addNumbers(10, 5)
.then((result) => console.log(result))
.catch((error) => console.log(error))
.finally(() => console.log("Operation complete"));
/* Expected output:15
Operation complete
*/
- Promise.race()
The Promise.race() method returns a promise that resolves or rejects as soon as one of the promises settles.
Key Characteristics:
Resolves with the first settled promise's value.
If a promise rejects first, the rejection is returned immediately.
Example:
const p1 = new Promise((resolve) => setTimeout(resolve, 200, "one"));
const p2 = new Promise((resolve) => setTimeout(resolve, 100, "two"));
Promise.race([p1, p2])
.then((response) => console.log(response))
.catch((err) => console.log(err));
// Expected output: "two"
const p3 = new Promise((_, reject) => setTimeout(reject, 300, "rejected"));
const p4 = new Promise((resolve) => setTimeout(resolve, 400, "four"));
Promise.race([p3, p4])
.then((response) => console.log(response))
.catch((err) => console.log(err));
// Expected output: "rejected"
Handling rejections in Promise.race() can be simplified to this explanation below:
- Promise.race() resolves or rejects as soon as the first promise settles.
- If the first settled promise resolves, race() resolves with its value.
- If the first settled promise rejects, race() rejects immediately.
- The remaining promises are ignored once one settles.
- This behavior makes Promise.race() useful for timeouts and early exits.
const p3 = new Promise((_, reject) => setTimeout(reject, 300, "rejected"));
const p4 = new Promise((resolve) => setTimeout(resolve, 400, "four"));
Promise.race([p3, p4])
.then((response) => console.log(response))
.catch((err) => console.log(err));
// Expected output: "rejected"
Understanding Promise.all(), Promise.any(), Promise.race(), and Promise.finally() is essential for writing efficient asynchronous code in JavaScript. These methods provide different approaches to handling multiple promises, allowing developers to manage tasks effectively.
Top comments (0)