On this page

JavaScript Promises

Enrico Hochkoeppler Profile

By Enrico Hochkoeppler

Web Developer & TutoriaLibre Founder

A Promise is a robust object representing the eventual completion (or failure) of an asynchronous operation and its resulting value. Historically, developers relied on callbacks to handle asynchronous logic, but as applications grew, this led to "callback hell"—deeply nested, unreadable code. Promises resolve this by providing a cleaner, more manageable "contract" for asynchronous actions.

The Lifecycle of a Promise​

When a Promise is created, it follows a specific lifecycle. A Promise can only settle once; after it moves from its initial state to a final state, it cannot change again.

Creating a Promise​

To generate a Promise, you use the new Promise constructor. This constructor requires an executor function, which runs immediately. The executor receives two arguments: resolve and reject.


const deliveryStatus = new Promise((resolve, reject) => {

  const isDelivered = true;



  // Simulating a delay for a delivery

  setTimeout(() => {

    if (isDelivered) {

      resolve("Package has arrived.");

    } else {

      reject("Delivery failed due to weather.");

    }

  }, 2000);

});

Consuming Promises: .then() and .catch()​

Once a Promise is created, you need mechanisms to handle the result when it eventually arrives. These are known as consumer methods.

The .then() Handler​

The .then() method is used to handle a fulfilled Promise. It accepts a callback function that receives the value passed into the resolve() function.

The .catch() Handler​

The .catch() method handles rejections. It acts as a centralized error handler, catching any issues that occurred during the Promise's execution or within the chain itself.


deliveryStatus

  .then((message) => {

    console.log("Success: " + message);

  })

  .catch((error) => {

    console.error("Issue: " + error);

  });

The .finally() Handler​

The .finally() method executes regardless of the outcome. It is commonly used for cleanup tasks, such as hiding a loading spinner on a webpage once a data request is finished.

Promise Chaining​

One of the most significant advantages of Promises is the ability to chain operations. Because each .then() call returns a new Promise, you can perform a sequence of asynchronous steps in a flat, vertical structure.


fetchUser(1)

  .then((user) => getProfile(user.id))

  .then((profile) => getSettings(profile.settingsId))

  .then((settings) => {

    console.log("User settings loaded:", settings);

  })

  .catch((err) => {

    console.error("An error occurred at some point in the chain:", err);

  });

In this example, if any of the three functions (fetchUser, getProfile, or getSettings) fails, the code will skip the remaining .then() blocks and immediately jump to the .catch() block. This is a massive improvement over callbacks, where error checking had to be performed manually at every level of nesting.

Professional Best Practices​

Found this helpful? Share the knowledge...

... or support this project to keep it alive!

Buy Me a Coffee

Previous

Callbacks

Next

Async/Await