Explaining Promises in JavaScript as if You Were a Kid

Let's use the analogy of asking your mom to bake cookies for you to explain JavaScript promises.

Imagine you're craving some delicious cookies, but you're too busy with your work to bake them yourself. So, you ask your mom if she could bake some cookies for you. She agrees, giving you her word that she'll bake them.

In JavaScript terms:

// momBakesCookies is a promise
const promise = momBakesCookies("chocolate chip");

At this point, your mom hasn't started baking yet. The promise is pending.

If your mom bakes the cookies, the promise is resolved, and you can enjoy them happily. But if for some reason she can't bake them, the promise is rejected, and you'll have to go hungry, perhaps seeking an alternative snack.

When a promise gets resolved, you do the next thing in a .then call. When a promise gets rejected, you do your backup plan in a .catch call.

momBakesCookies("chocolate chip")
  .then(eatCookies) // Yum! 🍪🍪🍪
  .catch(goHungry); // Oh no! 😢

Similarly, in JavaScript we use promises to retrieve data or perform actions asynchronously. When the promise resolves, we handle the success by executing the .then block, and when it rejects, we handle the error in the .catch block.

getSomethingWithPromise()
  .then((data) => {
    /* do something with data */
  })
  .catch((err) => {
    /* handle the error */
  });

Get my free, weekly JavaScript tutorials

Want to improve your JavaScript fluency?

Every week, I send a new full-length JavaScript article to thousands of developers. Learn about asynchronous programming, closures, and best practices — as well as general tips for software engineers.

Join today, and level up your JavaScript every Sunday!

Thank you, Taha, for your amazing newsletter. I’m really benefiting from the valuable insights and tips you share.

- Remi Egwuda