JavaScript Promises: Everything You Need to Know

Vinay PatelVinay Patel
3 min read

JavaScript Promises are a fundamental concept used to handle asynchronous operations in a more manageable and readable way.

They provide a cleaner and more manageable alternative to traditional callback-based code, helping to prevent "callback hell."

What is a Promise?

A Promise is an object that represents the eventual completion (or failure) of an asynchronous operation. A promise can be in one of three states:

  • Pending: The initial state before completion.

  • Fulfilled: The operation was successful.

  • Rejected: The operation failed.

Creating a Promise

You can create a promise using the Promise constructor, which takes an executor function with two parameters: resolve and reject.

  • then(): Used to handle the resolved value of the promise. It takes a function that gets executed when the promise is fulfilled.
const myPromise = new Promise((resolve, reject) => {
  let success = true;

  if (success) {
    resolve("Operation successful!");
  } else {
    reject("Operation failed.");
  }
});

Consuming a Promise

Promises are handled using .then(), .catch(), and .finally():

myPromise
  .then((result) => {
    console.log(result); // "Operation successful!"
  })
  .catch((error) => {
    console.error(error); // "Operation failed."
  })
  .finally(() => {
    console.log("Promise settled (either resolved or rejected).");
  });

Chaining Promises

Promises can be chained to perform sequential asynchronous operations.

myPromise
  .then((result) => {
    console.log(result);
    return new Promise((resolve) => resolve("Next operation"));
  })
  .then((nextResult) => {
    console.log(nextResult);
  })
  .catch((error) => {
    console.error(error);
  });

Promises API ( Handling Multiple Promises )

Promise.all()

→ This method accepts an array of promises and returns a new promise that resolves when all of the input promises are fulfilled.
→ If any promise is rejected, Promise.all() immediately rejects with that error.

Waits for all promises to resolve and returns an array of results. If any promise rejects, the entire operation fails.

const promise1 = Promise.resolve("First");
const promise2 = Promise.resolve("Second");

Promise.all([promise1, promise2])
  .then((results) => console.log(results)) // ["First", "Second"]
  .catch((error) => console.error(error));

Promise.race()

→ This method returns a promise that resolves or rejects as soon as the first promise in the array resolves or rejects.

Returns the result of the first resolved or rejected promise.

const promise1 = new Promise((resolve) => setTimeout(resolve, 500, "First"));
const promise2 = new Promise((resolve) => setTimeout(resolve, 100, "Second"));

Promise.race([promise1, promise2])
  .then((result) => console.log(result)) // "Second"
  .catch((error) => console.error(error));

Promise.allSettled()

→ This method returns a promise that resolves when all input promises have settled (either resolved or rejected).

not fail if one promise rejects

const promise1 = new Promise((resolve) => setTimeout(resolve, 500, "First"));
const promise2 = new Promise((resolve) => setTimeout(resolve, 100, "Second"));

Promise.allSettled([promise1, promise2])
  .then((result) => console.log(result))
  .catch((error) => console.error(error));

Promise.any()

→ This method returns the first fulfilled promise.
→ If all promises reject, it returns an AggregateError.

const promise1 = Promise.reject("Failure 1");
const promise2 = Promise.resolve("Success");
const promise3 = Promise.reject("Failure 2");

Promise.any([promise1, promise2, promise3])
  .then((result) => console.log(result)) // "Success"
  .catch((error) => console.error(error));

Async/Await: A Cleaner Alternative

The async/await syntax makes working with promises easier and more readable.

async function fetchData() {
  try {
    const result = await myPromise;
    console.log(result);
  } catch (error) {
    console.error(error);
  }
}

fetchData();

Error Handling in Promises

Errors in promises should be properly handled using .catch() or try/catch.

new Promise((_, reject) => reject(new Error("Something went wrong")))
  .catch((error) => console.error("Caught error:", error));

Happy coding! 🚀

0
Subscribe to my newsletter

Read articles from Vinay Patel directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Vinay Patel
Vinay Patel

Hi, My name is Vinay Patel, and I'm an aspiring software developer.