Welcome to Part 2 of our JavaScript promises series! In Part 1, we explored basic promise behaviors, including resolution, chaining, and rejection handling. Now, we’ll take things up a notch and delve into more advanced promise techniques like Promise.race()
, Promise.all()
, Promise.allSettled()
, and Promise.any()
.
Let’s dive into five more tricky questions that will help you master these advanced promise concepts.
Question 6: Promise.all()
– Handling Multiple Promises
const promiseA = Promise.resolve("A");
const promiseB = new Promise((resolve) => setTimeout(resolve, 100, "B"));
const promiseC = Promise.resolve("C");
Promise.all([promiseA, promiseB, promiseC]).then((results) => {
console.log(results);
});
Output:
["A", "B", "C"]
Explanation:
-
Promise.all()
waits for all promises to resolve before returning the results. - The resolved values are returned in the same order as the promises in the array, even if they resolve at different times. Here,
promiseB
takes longer butPromise.all
waits for it to complete before logging["A", "B", "C"]
.
Question 7: Promise.all()
with Rejection
const promiseD = Promise.resolve("D");
const promiseE = new Promise((_, reject) => setTimeout(reject, 50, "Error"));
const promiseF = Promise.resolve("F");
Promise.all([promiseD, promiseE, promiseF])
.then((results) => {
console.log(results);
})
.catch((error) => {
console.log("Caught:", error);
});
Output:
Caught: Error
Explanation:
- If any promise in
Promise.all()
rejects, the entire operation immediately rejects. - In this case,
promiseE
rejects after 50ms, so the.catch()
handler catches the error and logsCaught: Error
. The remaining promises are ignored once the rejection occurs.
Question 8: Promise.race()
– Fastest Promise Wins
const promiseG = new Promise((resolve) => setTimeout(resolve, 100, "Resolved G"));
const promiseH = new Promise((_, reject) => setTimeout(reject, 50, "Rejected H"));
const promiseI = new Promise((resolve) => setTimeout(resolve, 150, "Resolved I"));
Promise.race([promiseG, promiseH, promiseI])
.then((result) => {
console.log("Won:", result);
})
.catch((error) => {
console.log("Lost:", error);
});
Output:
Lost: Rejected H
Explanation:
-
Promise.race()
returns a promise that settles as soon as the first promise settles, whether it's resolved or rejected. - Since
promiseH
rejects the fastest (after 50ms), the.catch()
handler logsLost: Rejected H
.
Question 9: Promise.allSettled()
– Get All Results Regardless of Outcome
const promiseJ = Promise.resolve("J");
const promiseK = new Promise((_, reject) => setTimeout(reject, 50, "Error in K"));
const promiseL = new Promise((resolve) => setTimeout(resolve, 100, "L"));
Promise.allSettled([promiseJ, promiseK, promiseL]).then((results) => {
console.log(results);
});
Output:
[
{ status: "fulfilled", value: "J" },
{ status: "rejected", reason: "Error in K" },
{ status: "fulfilled", value: "L" }
]
Explanation:
-
Promise.allSettled()
returns an array of results after all promises settle (either fulfilled or rejected). - Each result is an object with a
status
field (fulfilled
orrejected
) and either avalue
(for fulfilled promises) or areason
(for rejected promises). - In this case,
promiseK
rejects whilepromiseJ
andpromiseL
fulfill, but we still get the results for all promises.
Question 10: Promise.any()
– The First Fulfilled Promise
const promiseM = new Promise((_, reject) => setTimeout(reject, 100, "Rejected M"));
const promiseN = new Promise((resolve) => setTimeout(resolve, 50, "Resolved N"));
const promiseO = new Promise((_, reject) => setTimeout(reject, 200, "Rejected O"));
Promise.any([promiseM, promiseN, promiseO])
.then((result) => {
console.log("First fulfilled:", result);
})
.catch((error) => {
console.log("All rejected:", error.errors);
});
Output:
First fulfilled: Resolved N
Explanation:
-
Promise.any()
resolves as soon as any promise is fulfilled. - Here,
promiseN
is fulfilled after 50ms, so the.then()
block logsFirst fulfilled: Resolved N
. - If all promises were rejected,
Promise.any()
would throw anAggregateError
, but that doesn’t happen in this case.
Conclusion:
In Part 2, we covered advanced promise techniques using Promise.all()
, Promise.race()
, Promise.allSettled()
, and Promise.any()
. These methods provide powerful ways to handle multiple asynchronous tasks simultaneously, each suited to different scenarios.
Here are the key takeaways:
-
Promise.all()
waits for all promises to either resolve or reject, and if any reject, the entire operation fails. -
Promise.race()
returns the result of the fastest promise, whether it's resolved or rejected. -
Promise.allSettled()
is useful when you need to wait for all promises to finish regardless of success or failure. -
Promise.any()
resolves with the first successfully fulfilled promise, ignoring rejections unless all promises fail.
By mastering these promise methods, you'll be well-equipped to handle even the most complex asynchronous workflows in JavaScript.
Happy coding!
Top comments (0)