Wednesday, May 21, 2025

Master JavaScript Promise Methods: all, allSettled, race, any & more

🚀 Mastering JavaScript Promise Methods: all, allSettled, allSettled, race, any, and More

JavaScript is built to handle asynchronous tasks — like fetching data from APIs, reading files, or delaying execution. One of the most elegant ways to manage asynchronous operations is through Promises.

But what happens when you have to manage multiple promises at the same time?

JavaScript gives you a toolkit of Promise utility methods that make this easy, powerful, and readable.

In this guide, we’ll go beyond the basics and explore:

  • Promise.all()
  • Promise.allSettled()
  • Promise.race()
  • Promise.any()
  • Promise.resolve() & Promise.reject()

🧩 What Is a Promise in JavaScript?

A Promise is a placeholder for a value that will be available now, later, or never. It has three states:

  • pending: The operation is ongoing.
  • fulfilled: The operation completed successfully.
  • rejected: The operation failed.

Promises make asynchronous code cleaner and more maintainable.


🔗 Promise.all() – When Everything Must Succeed

Promise.all() takes an array of promises and waits for all of them to fulfill. If even one fails (rejects), the whole operation fails immediately.

const p1 = Promise.resolve("Data 1");
const p2 = Promise.resolve("Data 2");
const p3 = Promise.resolve("Data 3");
Promise.all([p1, p2, p3])
.then(results => console.log(results)) // ['Data 1', 'Data 2', 'Data 3']
.catch(error => console.error(error));

❌ If one of the promises rejects:

const p1 = Promise.resolve("Data 1");
const p2 = Promise.reject("Something went wrong!");
const p3 = Promise.resolve("Data 3");
Promise.all([p1, p2, p3])
.then(console.log)
.catch(error => console.error(error)); // Outputs: Something went wrong!

🔍 Use Case: API calls where all data is required to proceed. For example, loading user info, posts, and comments together.


🧘‍♂️ Promise.allSettled() – When You Want the Full Picture

Promise.allSettled() waits for all the promises to complete, no matter whether they succeed or fail. It returns an array of objects with each promise's result.

const p1 = Promise.resolve("Success");
const p2 = Promise.reject("Failure");
const p3 = Promise.resolve("Another success");
Promise.allSettled([p1, p2, p3])
.then(results => console.log(results));

🔍 Output:

[
{ status: "fulfilled", value: "Success" },
{ status: "rejected", reason: "Failure" },
{ status: "fulfilled", value: "Another success" }
]

🔍 Use Case: Ideal when you want to process all results, even if some fail — like when uploading multiple files and showing a summary of what succeeded/failed.


🏁 Promise.race() – First One to Settle Wins

With Promise.race(), only the first promise that settles (fulfilled or rejected) is returned. All others are ignored after that.

const p1 = new Promise(resolve => setTimeout(resolve, 1000, "One second"));
const p2 = new Promise(resolve => setTimeout(resolve, 500, "Half second"));
Promise.race([p1, p2])
.then(result => console.log(result)); // 'Half second'

If the first one to settle is a rejection, the entire race will reject:

const p1 = new Promise((_, reject) => setTimeout(reject, 300, "Failed first"));
const p2 = new Promise(resolve => setTimeout(resolve, 1000, "Success"));
Promise.race([p1, p2])
.then(console.log)
.catch(console.error); // 'Failed first'

🔍 Use Case: Great for timeout handling — e.g., race your API call with a timeout promise.


🥇 Promise.any() – First to Succeed

Introduced in ES2021, Promise.any() returns the first fulfilled promise, ignoring rejections unless all of them fail.

const p1 = Promise.reject("Error 1");
const p2 = Promise.resolve("Success!");
const p3 = Promise.reject("Error 2");
Promise.any([p1, p2, p3])
.then(console.log) // "Success!"
.catch(console.error);

If all promises reject, you get an AggregateError:

Promise.any([
Promise.reject("Error A"),
Promise.reject("Error B")
])
.then(console.log)
.catch(err => console.error(err.errors)); // ['Error A', 'Error B']

🔍 Use Case: Try multiple strategies and accept the first success — like querying multiple redundant APIs or fallback services.

🛠 Promise.resolve() & Promise.reject() – Create Promises Instantly

These are helper methods to instantly create resolved or rejected promises.

Promise.resolve("Instant success").then(console.log); // 'Instant success'
Promise.reject("Instant fail").catch(console.error); // 'Instant fail'

🔍 Use Case: Useful in unit tests, mocks, or when you want to wrap a value in a promise context.


📊 Summary Table

 Method   Description   Rejects Fast?   Best Used When…  
 Promise.all()  Waits for all to succeed or fails on one reject  ✅ Yes  You need all promises to succeed
 Promise.allSettled()  Waits for all to finish, good or bad  ❌ No  You want results from all, regardless
 Promise.race()  Returns first settled result  ❌ No  You care about speed (first to finish)
 Promise.any()  Returns first fulfilled result  ❌ No  You want the first successful result

💡 Final Thoughts

JavaScript promises are powerful, and knowing how to use these methods helps you write faster, cleaner, and more reliable asynchronous code.

Whether you're:

  • Handling multiple API calls
  • Managing fallback strategies
  • Tracking mixed success/failure tasks
  • Or racing against time...

🎁 Bonus Tip:

You can combine these methods for advanced workflows — for example, race an API call with a timeout using Promise.race(), but also process results using Promise.allSettled() for full diagnostics.

No comments:

Post a Comment