Never Promise More Than You Can Perform in JavaScript!

Kapil Pant
3 min readMar 1, 2021

A small and basic explanation of promise and its states.

Hedgehogs are famous for their prickly spines, which they have everywhere except on their face, legs and bellies. These cute critters depend on their spines for defense, both while they sleep and when they face enemies.

We live in a world that is built on promises constructed by liars. When we hear this word “promise”, we are overwhelmed by its vibe, when taken in the positive manner. We all tend to be jovial thinking about its completion in the future. Let’s say, your father promised to buy you a brand new car, so, in return you’ll be amazed, but also be overjoyed due to a swamp of euphoria.

But, this is not the case with JavaScript. A “promise” in JavaScript is somewhat similar to real-world “promise” i.e., it is something that may be completed in future.

A real-world promise can either be completed or cannot be completed. But, if you think deeply, you’ll notice that it can also be there in the middle of “completed” and “not completed”. Similar is the case with promise in JavaScript.

3 possible states

A promise will always be in one of three possible states namely —

  • Fulfilled
  • Rejected
  • Pending

Before diving into the explanation of the above terms, let us discuss about the basics of promise in JavaScript.

What is a promise?

A promise is an object that may return a single value in future. A promise is generally resolved or rejected based on its basic definition. It is used to make asynchronous methods return values like synchronous methods. A promise is resolved using “.then” method. “.then” is a compulsory method for settling a promise. There is also a bonus method named “.catch”, which is used to deal only with the rejected cases.

Block diagram

Code snippet for you to try!

var mypromise = new Promise(function(resolve, reject){  let flag = 0;  // Try with "flag=1"  if(flag==0){    resolve("I am resolved");  }else if(flag!=0){    reject("I am rejected");  }}).then(function(response){  console.log(response);}).catch(function(err){

console.log(err);
}) // Try this code snippet using different values of "flag"!

States explanation

3 possible states of a promise

A promise is said to be resolved if the functionality mentioned inside a promise is completed without any errors. And, a promise is said to be rejected if the functionality mentioned inside a promise is not completed due to certain reasons. Hence, if a promise is on its way, and there is no settlement or rejection till date, then it is said to be in a pending state.

Conclusion

I’ve tried to accumulate basics of promise and its states in such a way that a beginner is able to understand it. But keep in mind, there is lot to learn and understand about promise apart form this.

--

--