DEV Community

Cover image for Exploring Essential Promise Methods in JavaScript.
Olaide Emmanuel
Olaide Emmanuel

Posted on

Exploring Essential Promise Methods in JavaScript.

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:

  1. Promise.all()
  2. Promise.any()
  3. Promise.race()
  4. Promise.finally()

Let's explore each method in detail with examples.

  1. ## 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"
Enter fullscreen mode Exit fullscreen mode
  1. 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"
Enter fullscreen mode Exit fullscreen mode
  1. 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
*/
Enter fullscreen mode Exit fullscreen mode
  1. 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"
Enter fullscreen mode Exit fullscreen mode
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"
Enter fullscreen mode Exit fullscreen mode

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"
Enter fullscreen mode Exit fullscreen mode

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.

Heroku

Amplify your impact where it matters most — building exceptional apps.

Leave the infrastructure headaches to us, while you focus on pushing boundaries, realizing your vision, and making a lasting impression on your users.

Get Started

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Explore a trove of insights in this engaging article, celebrated within our welcoming DEV Community. Developers from every background are invited to join and enhance our shared wisdom.

A genuine "thank you" can truly uplift someone’s day. Feel free to express your gratitude in the comments below!

On DEV, our collective exchange of knowledge lightens the road ahead and strengthens our community bonds. Found something valuable here? A small thank you to the author can make a big difference.

Okay