Skip to main content

Command Palette

Search for a command to run...

OPERATION PROMISE: The Digital Battlefield

Published
6 min read
OPERATION PROMISE: The Digital Battlefield

Just imagine that you are a Major at the Indian Army Command Center. You have a very critical mission at this time and the mission is to Capture the Enemy's Base.

In early days we used Callbacks. Take it like a game of Chinese Whispers where you told soldier X to find the map then you had to tell soldier Y to find the keys and then soldier Y had to tell soldier Z to start the car.

If soldier Y tripped then the entire line broke because of a single soldier. And that time you couldn't see what was happening. We called it Callback Hell.

The New Order: What is a Promise?

A Promise is nothing else just like a commitment just take a real world example such as when you give an order to a soldier in return you want the result but soldiers don't give you the result immediately, instead they give a Promise that they will complete the given task.

Now you have sent the all soliders in to the field and you don't just sit in your room. You prepare the entire battle you check the weather, you prepare the rations and plan the next move. You are called asynchronous.

The 3 States of a Soldier

Every mission includes these three states whcih are used to handle the entire mission.

  • Pending

  • Fulfilled/Resolved

  • Rejected

Pending State

On pending state the soldier is on the way but the result is still unknown.

Fulfilled

On this state not only soldier but everyone celebrate it because this is the state where soldiers return with the enemy flags It shows that the mission is accomplhished and they are coming back to the base.

Rejected (Failure)

On this state you can understand it like this, suppose the soldiers where they were being sent there was a bridge between the command base and the destination where they wanted to go. So the bridge was broken and the soldiers couldn't cross it. It means the mission was postpond at that time. In promises world this is called rejected.

Mission Issuing the Order

In JavaScript this is how you send a soldier on a mission. It's not difficult to understand issuing the order means you are preparing the soldiers to send them.

const captureBase = new Promise((resolve, reject) => {
    let baseCaptured = true; // The battlefield reality to understand promises in js bro...

    console.log("Soldier: Major The mission is started");

    setTimeout(() => { // It simulates the time which is taken for the mission
        if (baseCaptured) {
            resolve("Sir! We captured the base. Now it is under our control"); // On this state the mission is accomplished
        } else {
            reject("We can not cross the bridge it is broken"); // On this state the mission is failed
        }
    }, 2000);
});

You can handle the report very easily.

You don't wait for anything you can directly tell the soldiers what to do after accomplishing the mission.

  • .then(): If you succeed, hoist the flag.

  • .catch(): If you fail, call for backup.

  • .finally(): Whether you win or lose return to base for dinner.

captureBase
    .then((msg) => console.log("Message:", msg))
    .catch((err) => console.log("Error:", err))
    .finally(() => console.log("Major: All units must return for dinner."));

The Shocking Comparison

Old Callback Way (The Jungle)

New Promise Way (The Command Center)

Code moves to the right (Pyramid).

Code moves downwards (Linear).

Hard to track errors.

One .catch() handles everything in your code.

You lose control of the flow in your code.

You stay in control at the top.

Squad (Static Methods)

In some critical missions you need a squad because one soldier won't be enough for that mission.

The Joint Strike (Promise.all)

Suppose you send 3 soldiers to 3 different location for the battle if all get success then you win otherwise if 1 soldier fails then the whole mission is a failure.

  • Use Case in real softwares, such as loading a user's profile, photos, and settings. You need all three to display the page.

The Full Report (Promise.allSettled)

You send 3 scouts but in this case you don't care about the result if they fail or secceed instead you just want a report from everyone regarding what they saw.

  • Use Case in real world software like sending 8 emails, you want to know which ones were sent and which ones bounced at that time.

The Scout Race (Promise.race)

You send 3 scouts to find a secret path as soon as the first one returns whether they found a secret path or just found an error, you immediately take action on that.

  • In real world software we use it like setting a 6 second of timeout. If the data doesn't come in 6 seconds, the Timeout Error wins the race.

The Backup Plan (Promise.any)

Lets understand Promise.any like some spies suppose you send 3 spies to find the location of your enemy. As soon as one spy succeeds you celebrate that and you ignore the other ones who failed.

  • In real world software we can see the usecase like Fetching data from 3 different servers. Suppose there are 3 servers, server A, server B, and server C. If Server A is down, but Server B is up and it's running so you take data from Server B.

The Final Upgrade: Async/Await

In modern warfare, we use Async/Await. It makes the code look like a simple list of commands, but it uses Promises secretly in the background. Async/Await in JavaScript allows you to write asynchronous code in a clean way which makes it easier to read, understand and maintain the code while working with promises. Async functions always return a Promise. Await keyword pauses the exectuion of the code until the Promise is resolved or rejected. The code becomes more readable as compare to .then() and .catch() chaining which makes the code frustrating to read if it gets very big. Async and await also make error handing very easy by using try.....catch.

async function executeMission() {
    try {
        const report = await captureBase; // It waits here until the promise is resolved or rejected
        console.log("Major reads report:", report);
    } catch (error) {
        console.log("Major handles crisis:", error);
    }
}

This was the journey of Promises in JS. I tried my best to explian it in a story form to make you understand what happens in Promises behind the scenes. Instead of using a lot of .then() in modern codes we use async and await to make our code maintainable and readable which handles all of these promised itself.

More from this blog

Baloch Coder

12 posts

Deep dives into web development and code logic. A technical journal of my learning journey featuring cohort tasks, project walkthroughs, and modern tech explorations.