DEV Community

Sreekar Reddy
Sreekar Reddy

Posted on • Originally published at sreekarreddy.com

🤞 Promises Explained Like You're 5

I promise to call you when I'm done

Day 52 of 149

👉 Full deep-dive with code examples


The Pizza Order

You order pizza for delivery.

The restaurant gives you a promise:

  • "Your pizza will arrive" (pending)
  • Eventually: "Pizza's here!" (fulfilled) 🍕
  • Or: "Sorry, we're out of dough" (rejected) ❌

JavaScript promises work the same way!


The Problem with Callbacks

Remember callback hell?

doA(function () {
  doB(function () {
    doC(function () {
      // 🌀 Spiral of doom
    });
  });
});
Enter fullscreen mode Exit fullscreen mode

Promises to the Rescue

doA()
    .then(() => doB())
    .then(() => doC())
    .then(() => done!)
    .catch((error) => handleError);
Enter fullscreen mode Exit fullscreen mode

Flat! Readable! Error handling in one place!


Three States

State Meaning
Pending Still working on it
Fulfilled Success! Here's the result
Rejected Failed! Here's the error

Creating a Promise

const myPromise = new Promise((resolve, reject) => {
  if (success) {
    resolve("Here's your data!");
  } else {
    reject("Something went wrong!");
  }
});
Enter fullscreen mode Exit fullscreen mode

In One Sentence

Promises represent a future value that will eventually be available, making async code cleaner than callbacks.


🔗 Enjoying these? Follow for daily ELI5 explanations!

Making complex tech concepts simple, one day at a time.

Top comments (0)