Skip to main content

Command Palette

Search for a command to run...

🀞 Promises Explained Like You're 5

Published
β€’1 min read
S

Building AI systems and writing about how they actually work. Master of AI @ University of Technology Sydney. Previously B.Tech CS with focus on IoT. I believe the best way to learn is to explain. That's why I'm documenting tech concepts with simple analogies (@sreekarreddy.com). AWS Certified β€’ Azure AI Certified β€’ Neo4j Professional β€’ Google Data Analytics When not coding: exploring Sydney, working on side projects, and teaching tech to anyone who'll listen.

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
    });
  });
});

Promises to the Rescue

doA()
    .then(() => doB())
    .then(() => doC())
    .then(() => done!)
    .catch((error) => handleError);

Flat! Readable! Error handling in one place!


Three States

StateMeaning
PendingStill working on it
FulfilledSuccess! Here's the result
RejectedFailed! 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!");
  }
});

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.

More from this blog

esreekarreddy

132 posts