JavaScript

What is a Promise Object in JavaScript

In JavaScript the promise objects are used to work with the asynchronous operations. The concept of promise may sound complicated at first but in reality they are quite simple; We can understand JavaScript promises by comparing them with real world promises using layman’s terms.

In everyday life we make promises to show our commitment. Similarly in JavaScript we make a promise object when we need to be committed to executing a block of code.

For example, when we send a request to fetch data from an API through our code, the API takes time to respond. In the meantime the JavaScript interpreter moves onto the next block of code but we want to execute some piece of code after the fulfilment or rejection of the response. Now, if we use the promise object, we can execute the desired line of codes upon the fulfilment or rejection of the API response.

The JavaScript promise objects can have three different states i.e:

  • Pending
  • Fulfilled
  • Rejected

The promise is in pending state when the result of the promise object is undefined; it is fulfilled when the result has a value and rejected when the result is an error. For instance, In the above example if we have sent the request to the API and are awaiting for the data then the promise is in pending state. If the API successfully sends the data then the promise is fulfilled and if the code cannot connect with the API then the promise has been rejected.

What are promises in JavaScript

As mentioned above, asynchronous operations in JavaScript are handled through promises. Asynchronous JavaScript mainly refers to the functions that are running in parallel with the main program.

In JavaScript events and callback functions were used to handle asynchronous operation before promises. Promises were added in the ES6 version of JavaScript in 2015. Although callback functions and events were useful they still had their limitations. Callback hell was the biggest drawback of the usage of callback functions.

Promises are perfect for handling asynchronous operations as they can handle several asynchronous operations and are way better at handling errors than events and callbacks.

How Promises Work in JavaScript

Asynchronous functions are functions that run parallel to the main program. These functions work separately from the main program and notify the calling thread of their success, failure or progress.

The promise object in JavaScript has one of three states:

  • pending: It is the state of the promise object between its initialization and completion.
  • fulfilled/resolved: It is the state which indicates that the operation of the promise object was successful.
  • Rejected: It is the state which indicates that the operation of the promise object was unsuccessful.​

Creating a simple promise object in JavaScript

Here we will learn to create a promise object in just a few simple steps:

  1. In JavaScript a promise object is created using a constructor “new Promise()”. This constructor takes a call back function with two arguments as an argument.
  2. The code that is required in order to perform the promised task is written in the body of the call back function.
  3. If the task is successfully performed then the promise is resolved/fulfilled; otherwise the promise is rejected/unfulfilled.
  4. There are two methods associated with the promise object, the then() and the catch() method. These methods are (respectively) called if the promise is resolved ​or rejected.

Note: The browser console is used for the demonstration of examples in this article.

JavaScript promises are created by using the new Promise() constructor:

const myPromise = new Promise();

The new Promise takes two different parameters. One of these parameters is for success (incase the promise is resolved) and the other one is for failure (incase the promise gets rejected):

const myPromise = new Promise((resolve, reject) => {
   // condition// condition
});

Finally, we define the body of the promise object. We give it a condition which will only be met if the promise is resolved:

const myPromise = new Promise((resolve, reject) => {
   let condition = true;  
   
   if(condition) {    
       resolve('Promise is resolved.');  
   } else {    
       reject('Promise is rejected.');  
   }
});

Now let’s learn to use our newly created promise object. There can only be two different end results for a promise object; it can either be a resolved or a rejected promise.

then() method : The then() method defines what will happen next if a promise gets resolved.

myPromise.then();

In this example we are using the then() method to log a message (that we got from the Promise) to the console.

myPromise.then((message) => {
   console.log(message);
});

catch() method : Similarly, the catch() method defines what will happen next if a promise fails.

myPromise.then((message) => {
   console.log(message);
}).catch((message) => {
   console.log(message);
});

It can be written in two different ways; separately or in combination with the then() method. In case the promise is unfulfilled, it will execute the catch() method and this time a different message will be shown on the console.

Conclusion

Promises in JavaScript are objects that are used as an alternative of callback functions and events when handling asynchronous operations in JavaScript. Promises can have three different states i.e. pending, fulfilled or unfulfilled. In the pending state the promise object is awaiting the value thus it has no value. In the fulfilled state it has the resolved value and in the unfulfilled state it has the reason why the promise was not resolved. This post was a thorough guide about promise objects in JavaScript.

About the author

Shehroz Azam

A Javascript Developer & Linux enthusiast with 4 years of industrial experience and proven know-how to combine creative and usability viewpoints resulting in world-class web applications. I have experience working with Vue, React & Node.js & currently working on article writing and video creation.