An introduction to JavaScript Promises

Promises.png

What is a promise?

According to MDN, The Promise object represents the eventual completion (or failure) of an asynchronous operation and its resulting value.

In simple words, Promises in JavaScript could be taken as an analogy to real-life promises. Let me explain it with the help of an example.

Imagine the time when you were 10 years old (Oh! Those Good Old Days) and you have asked for that remote control car from your parents. They have promised to buy when you perform well in your exams. Now, that promise can take the following states:-

  • Fulfilled - You scored well in exams. And your parents have fulfilled their promise of buying you the car.
  • Rejected - You were not able to score well in exams. So, your parents have rejected your request. (Better luck next time).
  • Pending - You have given your exams. But you are waiting for the results to be out. So, the Promise is in Pending state. It hasn’t been fulfilled or rejected yet.

You saw the promises in real life. Now, Let's consider how promises works in the context of an HTTP Request. Suppose you want to fetch some data and you have sent an HTTP Request. The server will return a response to our request which would contain some data.

You could send an HTTP Request using Fetch API which returns a promise. It could be:-

  • Fulfilled - If we get the response from the server.
  • Rejected - The server rejected the error due to some error.
  • Pending - You have sent the request but waiting to get the response from the server.

I hope you have got a basic idea of Promises through this article. Do let me know if I have missed anything. I am always willing to learn. Thanks to Dinys Monvoisin for pointing out a better analogy for Pending State.