Skip to main content

Command Palette

Search for a command to run...

Promises - You Can Actually Trust (Will Never Betray)

Updated
7 min read
Promises - You Can Actually Trust (Will Never Betray)

This article will help you to understand the concept of JavaScript Promises in a simple and practical way with proper real life analogies. If you are a Marvel fan, or have watched all the "Avengers", you are gonna relate and understand this article easily.

What is a Promise in JavaScript ?

We have all been there when someone says : "I Promise"... and somehow (intensionally or unintensionally) it doesn't happen or it's broken or betrayed.

But forget that and welcome to the world of JavaScript, where promises are meant to be kept, either it will get fulfilled or will get rejected and handled, but never betrayed.

Let's understand this in the universe of Avengers.......

Imagine Nick Fury got to know that the infinity stones are scattered across the universe, he called Avengers and assign different missions. But when a mission starts, result does not come instantly. Avengers have to travel, fight and survive before returning.

This Mission can be called as Promise in JS.

In javaScript, Promise is an object that represents a task that will complete in the future, just like the Avenger's mission.

It does not give the result immediately, but gives a commitment that "I will return with either success or failure, there is no mid-way". Just like the Avenger leaving for a stone, you don't know the result yet, but you trust that there will be a result.

const getTimeStone = new Promise((resolve, reject) => {
  const missionSuccess = true;

  if (missionSuccess) {
    resolve("Time Stone Found");
  } else {
    reject("Mission failed");
  }
});

Why Do We Need Promises ?

Imagine Nick Fury kept asking every minute to each Avenger : "Did you get the stone"... "What is the update now".... "Did you get it now?".... you know this is not a good way to run any mission, It's messy. Each Aveneger is in different space and fighting with enemy, they need time.

So instead of freezing the whole universe and waiting for one Avenger to fight and come back, Nick Fury sends them on the mission and continues coordinating with other Avengers.

In JavaScript also, some tasks like Fetching data from API's, Reading a file, Connecting to Database, etc. takes time. JS also do the work like Nick Fury, It sends the task, continues running other code, and waits for the result in the background.

A Promise is like an Avenger saying “I’ll either return with the stone… or I won’t. But you’ll definitely get an answer.”

No constant checking. No chaos. Just trust in the mission.

States of Promise

Every Infinity Stone mission can only be three outcomes :

  1. Pending : Avenger has left, the battle is happening, but we don't know the result yet.

  2. Fulfilled / Succeeded / Resolved : The Avenger returns with the Stone, mission succeeded, let's celebrate.

  3. Rejected / Failed : Thanos interferes and the mission failed, somebody will come to rescue the Avenger.

Most important part is, once the mission is failed or succeeds, result cannot be changed.

Exactly same thing happens in JavaScript........

JS Promise also have the same 3 states :

  1. Pending : Promise is being executed, we don't have the result yet.

  2. Fulfilled / Succeeded / Resolved : Promise got resolved successfully, now .then comes into picture to perform the operations after success, just like celebration.

  3. Rejected / Failed : Promise got rejected and error occured, .catch comes into picture to handle the rejection error.

Methods of Promise

Let's take a look how different Promise methods will look like inside the Avengers Universe.

Just like there would be different scenarios during the Avengers mission, for example :

  • There would be seperate instructions to follow after winning or losing for each Avenger like : you need to come back to a specific place after winning and a different place after losing, just like Instance methods in JS.

  • There would be a grouped instructions to follow after winning or losing as a team for example : what would happen if one of us lose, or we all lose or we all succedded, what would be the result of mission as a team, just like Static methods in JS.

Exactly in JS we can devide Promise methods into 2 parts :

  • Instance Methods : These methods are used to work with the outcome of a specific insatnce of promise. following methods come under this category :

    • .then() : This is like celebration after mission success, if the Promise is fullfilled in JavaScript .then() runs.

    • .catch() : This is like Nick Fury sent someone to rescue the avenger if lose, In JS if the Promise got rejected, .catch() comes to handle the rejection.

    • .finally() : This is like the final reporting of Avengers, weather the mission is succeeded or failed there is always a discussion afterward. In JavaScript also finally() runs, no matter what the outcome of Promise is.

getSpaceStone
  .then(result => {
    console.log("Victory:", result);
  })
  .catch(error => {
    console.log("Emergency:", error);
  }).finally(() => {
    console.log("Mission concluded. Avengers regroup.");
  });
  • Static Methods : These methods are called on the Promise class to create or combine promises, following methods come under this category:

  • Promise.all() : This is like Endgame mission for Avengers, the Avengers split into teams to collect all stones, if any of the Avenger failed to collect the Infinity Stone, the mission will be failed. Exactly in JavaScript if any of the promise in the iterable failed, the whole promise wil return reject.

Promise.all([
  getSpaceStone(),
  getTimeStone(),
  getRealityStone()
])
.then(stones => console.log("All stones collected:", stones))
.catch(error => console.log("Mission collapsed:", error));
  • Promise.all()Promise.any() : For some missions we don't need everyone to succeed, If even one Avenger defeats the enemy, universe will be safe, similarly in JavaScript, while using Promise.any() with iterables in promise, if any of the iterable got resolved, the whole Promise will be resolved.
Promise.any([
  ironManAttack(),
  thorStrike(),
  captainShield()
])
.then(result => console.log("Earth saved by:", result))
.catch(() => console.log("All heroes failed."));
  • Promise.allSettled() : Imagine nick fury says : "I don't care who succeeds or fails, I want everyone's report after mission end.", that is exactly what Promise.allSettled() does with Promises, it waits for all the promise iterables to finish weather they succeed or fail, and provide result.
Promise.allSettled([
  getSpaceStone(),
  getTimeStone(),
  getRealityStone()
])
.then(results => console.log("Mission reports:", results));

Conclusion

Just like Nick Fury assigns missions to each Avenger without holding the other tasks, there is something similar happening behind the scenes in JavaScript.

The "Event Loop" is the Nick Fury of JavaScript, whenever we write asynchronous code like API calls, DB connections etc. JavaScript does not stop everything and wait for them to complete, instead of that, it hand over those tasks to the Web APIs or queue and keep moving forward the call stack.

And the Event Loop stands there, constantly watching like "Nick Fury" managing the Avengers.

When a task is completed, whether it’s successful or failed, the Event Loop takes that result and pushes it back into the call stack at the right moment.

Just like Fury coordinating with Thor, Iron Man, and other Avengers for their missions.

Promises are the structured mission reports :

.then() is the celebration.
.catch() is damage control or rescue.
Promise.all() is Endgame strategy.

Event Loop : It’s the silent strategist making sure everything runs in order.

That’s the beauty of JavaScript, It doesn’t panic, It doesn’t freeze the universe, It assigns the mission, It waits patiently, And it delivers the outcome.

A Promise may resolve, a Promise may reject, but it will never betray, and that’s why, as developers, we trust it.