DEV Community

Cover image for What if JavaScript Promise Methods were IPL Teams?
Tushar Kumar Raj
Tushar Kumar Raj

Posted on

What if JavaScript Promise Methods were IPL Teams?

We have all promised or got a promise from someone at some stage of life right? Promises like, "I will call you tomorrow" or "I won't do that next time" or "ee sala cup namde" but it's not necessary that every promise will get fulfilled everytime right? A promise alone doesn't guarantee success.

Strangely enough, it's similar in JavaScript, a promise represents something that is expected to be completed in future, it can either successfully complete or fail completely. But you might be wondering, why add something that doesn't guarantee success or why are we talking about a "promise" in programming?


What is a Promise?

Well, JavaScript in itself is a single threaded programming language, which means it can do one task at a time, so if we have written long code for a website, then entire application will wait for API calls or database responses one by one before executing the next lines of code, which would make it look like its frozen. So promise was introduced as a placeholder for tasks that might resolve in future, this made it possible for execution of other code while waiting for long running operation to complete, making everything smoother.

It is written as:

const promise = new Promise((resolve, reject) => {
  const condition = true;

  if (condition) {
    resolve("promise kept");
  } 
  else {
    reject("better luck next time");
  }
});

promise
  .then((res) => console.log(res))
  .catch((err) => console.log(err));
Enter fullscreen mode Exit fullscreen mode

We have created a promise using its constructor function. It consists of an executor function (for resolving promise) with 2 parameters.

In real life every promise has a condition right? "I will call you tonight" is a condition, if they call you tonight then the promise was "resolved" or else it was "rejected", while you wait for night to fall the promise is "pending".

Similarly here, the promise stays in pending state until either resolve() or reject() is called, the resolve parameter runs when the condition is true, while the reject parameter runs when the condition is false. These are the three states of promise.

.then() is used to handle the value when the promise resolves, while .catch() handles the error if the promise rejects.

This promise sounds cool right? but what if multiple promises are running together? Wouldn't it be interesting to learn about them through IPL teams analogy?


Promise.all() - Royal Challengers Banglore's Calculator

It's best time to be an RCB fan but you can never forget the good old days. Every time during mid season, our calculators were out and we calculated scenarios like:

  • We have to win all the remaining matches
  • Mumbai Indians should beat Delhi Capitals
  • Kolkata should lose their next match by high margin

If all these scenarios went our way then only RCB qualified. Otherwise, knocked out.

This is exactly how Promise.all() works:

Promise.all([match1(), match2(), match3()])
Enter fullscreen mode Exit fullscreen mode

In this code, it waits for all promises to resolve, if any one of the match function returns reject, then the entire promise gets rejected, similar to how RCB getting knocked out of tournament if even one scenario doesn't go their way. If all promises resolve then it returns array of their result in same order.

This is useful when you need all tasks to succeed, for example, fetching user data, posts, and notifications together before rendering a dashboard.


Promise.any() - Mumbai Indian's Qualification Hope

Usually Mumbai Indians start the IPL with series of losses which in the end leads to dependence on one of many scenarios to go their way:

  • They must win their final game
  • Chennai Super Kings must defeat Punjab Kings
  • Chennai Super Kings vs Punjab Kings get washed out due to rain

Unlike RCB, they're fine as long as at least one of these conditions get satisfied.

This describes Promise.any():

Promise.any([scenario1(), scenario2(), scenario3()])
Enter fullscreen mode Exit fullscreen mode

It resolves as soon as one promise fulfills, it returns reject only when all promises get rejected. Similar to Mumbai Indian's case where they needed only one scenario to go their way.

This is useful when you have multiple backup sources and you just need one successful response.


Promise.race() - Sunrisers Hyderabad's Start

The Sunrisers Hyderabad has adopted a super aggressive approach in batting for quite some time now. But they have failed miserably when they are put under pressure during first powerplay. If powerplay doesn't go well then SRH crumbles, and fails to express themselves.

Similar to this, is our Promise.race():

Promise.race([powerplay(), middleOvers(), deathOvers()])
Enter fullscreen mode Exit fullscreen mode

It settles as soon as the first promise settles, powerplay in our analogy. It doesn't matter if the result of it is success or failure, first outcome decides everything, So if the powerplay is ruined whole match is ruined similar to SRH.

A common use case of Promise.race() is implementing timeouts. For example, you can race an API request against a timer. If the API responds first, you get the data. If the timer finishes first, you treat it as a timeout error.


Promise.resolve() - The Chennai Super Kings Dominance

In past few years, CSK has been under a decline, but back in the days there used to be a saying "IPL is a tournament where teams participate to face CSK in final", it was like CSK's final qualification was guaranteed even before the season started.

Similar to this is Promise.resolve():

Promise.resolve("Qualified for the Final")
Enter fullscreen mode Exit fullscreen mode

It immediately returns a fulfilled promise, there are no conditions, no waiting, no dependency. Similar to how CSK's chances used to be for the final qualification.

This is useful when you already have a value but want to return it as a promise. For example, if a function is expected to return a promise, you can use Promise.resolve() to wrap a normal value inside a resolved promise.


Promise.reject() - Poor Punjab Kings and Delhi Capitals

Punjab Kings and Delhi capitals have never won the IPL trophy, when people think of IPL the chances of winning for these two is mostly assumed to be a zero. It is like exact opposite of CSK.

Similar to this is Promise.reject():

Promise.reject("Eliminated")
Enter fullscreen mode Exit fullscreen mode

Its the direct counterpart of Promise.resolve(), it immediately returns rejected promise and triggers .catch().

It is often used to immediately return an error in a function that is expected to return a promise but you already know that it should fail under certain condition.


Promise.allSettled() - The Points Table

Not a team here but the points table itself. The points table keep the record of each team in a visually understandable manner. The result of a match doesn't matter, its job is to show the result.

That's how Promise.allSettled() works:

Promise.allSettled([match1(), match2(), match3()])
Enter fullscreen mode Exit fullscreen mode

It waits for all promises to resolve, it doesn't matter if a promise fulfill or reject. It's job is to show the result of all promises in an array. Yes, it resolves an array:

[
  { status: "fulfilled", value: "RCB won" },
  { status: "rejected", reason: "CSK lost" },
  { status: "fulfilled", value: "PKBS won" }
]
Enter fullscreen mode Exit fullscreen mode

This is what you will receive from Promise.allSettled(). For fulfilled status it shows the value and for rejected status it shows the reason.

Promise.allSettled() is useful when you want to run multiple independent tasks and need a complete report of all outcomes even if some fail. Great for debugging.


It was Never just About IPL

IPL season of every team begins with a promise, just like every async operation in JavaScript.

But what matters is not just whether something succeeds or fails, but how multiple outcomes are handled together.

And that's what Promises are, different ways of handling uncertainties, just like how every IPL team handles their own. And maybe that's the reason IPL analogy fits so well.

Top comments (0)