Skip to main content

Command Palette

Search for a command to run...

JS Promises Explained for Beginners

Updated
2 min read

What problem Promises solve

Before Promises, JavaScript used "Callbacks" to handle things that take time (like fetching data from API's). If you had many tasks, you would end up with Callback Hell—code that grows like a triangle and is almost impossible to read. Promises were created to fix this mess, making our code look clean, organized, and easy to follow.

Promise states

We can compare a Promise to a real-life promise. When you make one, it can be in one of three states:

  1. Pending: The initial state. The task hasn't finished yet (like waiting for your order to be delivered).

  2. Fulfilled: Success! The task finished perfectly (The order arrived).

  3. Rejected: Failure. Something went wrong (The order was not arrived and gives the reason).

Basic promise lifecycle

The lifecycle is the journey of a Promise. It starts in the Pending state the moment it is created. From there, it can only go to one of two destinations: Settled (Fulfilled) or Settled (Rejected). Once a promise is settled, it cannot change its state again.

Handling success and failure

To actually use the result of a Promise, we use two main "handlers":

  • .then(): This block runs only if the promise is Fulfilled. It receives the data you were waiting for.

  • .catch(): This block runs only if the promise is Rejected. It helps you catch the error so your whole app doesn't crash.

JavaScript

myPromise
  .then((data) => console.log("Success:", data))
  .catch((error) => console.log("Error:", error));

Promise chaining concept

This is the "Callback Hell" killer. Promise chaining allows you to join multiple asynchronous tasks one after another. Instead of nesting code inside code, you just keep adding .then() blocks. Each .then() returns a new promise, passing the result down the chain. It says like this: "Do this, then do that, then do this other thing."

This is a diagram of all learnings:


In JavaScript, just like in life, not every promise gets fulfilled—but as long as you know how to handle the rejections, you're on the right track. Happy coding!