🤝 Mastering Promises in JavaScript — From Callback Hell to Promise Heaven 🚀

Amandeep SinghAmandeep Singh
3 min read

Let’s face it — the first time someone says “promise” in JavaScript, you expect it to be like a real-life promise.

But then JavaScript hits you with:

“I promise… but you’ll have to .then() and .catch() me.” 🤯

We’ll go from the basics of Promises to advanced tricks — with clear examples, funny memes, and zero callback hell 🧵👇


🧠 What is a Promise?

A Promise is an object representing the eventual completion (or failure) of an async operation.

In desi terms:

“Aapka kaam ho jaayega, bas thoda intezaar kijiye. :)”


🧵 The Lifecycle of a Promise

A Promise can be in one of 3 states:

State Description pending Initial state – still waiting
fulfilled Operation completed successfully 🎉
rejected Operation failed 💥


🏗️ Creating a Promise

const myPromise = new Promise((resolve, reject) => {
  const success = true;
   if (success) {
    resolve("✅ Promise fulfilled!");
  } else {
    reject("❌ Promise rejected!");
  }
});

Note: resolve is for success, reject is for failure.


⚡ Consuming a Promise

myPromise
  .then((result) => {
    console.log(result); // ✅ Promise fulfilled!
  })
  .catch((error) => {
    console.log(error); // ❌ Promise rejected!
  })
  .finally(() => {
    console.log("Cleanup logic here ✅");
  });
  • .then() is like “what to do when it works”

  • .catch() is like “what to do if it fails”

  • .finally() is like “jo bhi ho, ye toh karna hi hai”


🧩 Real-Life Example: Simulate API Call

function fetchData() {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      const data = { user: "Amandeep", id: 1 };
      resolve(data);
    }, 2000);
  });
}

fetchData()
  .then((res) => console.log("Data:", res))
  .catch((err) => console.error("Error:", err));

🧠 Simulating an API call with setTimeout – notice the async nature!


🧟 Callback Hell vs Promises

Before Promises:

getUser((user) => {
  getPosts(user, (posts) => {
    getComments(posts, (comments) => {
      console.log(comments);
    });
  });
});

💀 Callback Hell*: a pyramid of doom!*

With Promises:

getUser()
  .then(getPosts)
  .then(getComments)
  .then(console.log)
  .catch(console.error);

🎉 Much cleaner, and easier to debug!


🔗 Chaining Promises

new Promise((resolve) => resolve(5))
  .then((val) => val * 2) // 10
  .then((val) => val + 1) // 11
  .then(console.log);     // logs 11

Each .then() gets the value from the previous one. It's like a relay race 🏃‍♂️🏃‍♂️🏃‍♂️


🤯 Common Mistake: Forgetting to Return

doSomething()
  .then((res) => {
    doSomethingElse(res); // ❌ returns undefined
  })
  .then((res) => {
    // 'res' is undefined!
  });

✅ Fix:

doSomething()
  .then((res) => {
    return doSomethingElse(res); // ✅ return the next promise
  })
  .then((res) => {
    // 'res' has correct value now
  });

🧠 Promise.all – Run Multiple in Parallel

Promise.all([
  fetchUser(),
  fetchPosts(),
  fetchComments(),
]).then(([user, posts, comments]) => {
  console.log({ user, posts, comments });
});
  • Waits for all Promises to resolve.

  • Fails fast if any one fails.


🕵️‍♂️ Promise.race – First to Finish Wins

Promise.race([
  slowNetworkCall(),
  timeout(3000),
]).then(console.log);
  • Returns the result of the first settled promise.

  • Use for timeouts or fallback strategies.


🧨 Promise.reject() and Promise.resolve()

Create immediate Promises for testing or defaults:

Promise.resolve("Instant value");
Promise.reject("Instant error");

🧙 Async/Await — The Promise Superpower

async function getData() {
  try {
    const user = await fetchUser();
    const posts = await fetchPosts(user.id);
    console.log(posts);
  } catch (err) {
    console.error("Oops!", err);
  }
}
  • Makes async code look synchronous 😍

  • Under the hood? Still uses Promises!

💡 Think of async/await as sugar on top of Promises 🍭


🧶 Final Meme

When you finally master Promises and your async code works like butter
“Arrey maza aa gaya!” 😎

0
Subscribe to my newsletter

Read articles from Amandeep Singh directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Amandeep Singh
Amandeep Singh

At GetReplies we are building a SaaS product to craft personalized emails, messages to target 10% reply rate. Zolo fosters impactful contributions as an SDE-III, where frontend engineering expertise drives scalable web solutions. Proficiencies in ReactJS, Next.js, and Redux Toolkit enable the creation of user-centric, high-performance applications. Success is achieved through seamless collaboration and continuous improvement.