What is a promise in Javascript

What is a promise

In Javascript, a promise is a special object used to handle asynchronous operations. It allows us to track the completion of the asynchronous operation.

The internal properties of a promise

A promise has three internal properties, Prototype, PromiseState, and PromiseResult.

image.png

The PromiseResult property stores the data to which the promise gets resolved or rejected.

The PromiseState property stores the information about the current state of a promise. A promise can have one of three states

  • pending: A promise starts in the pending state. A pending promise indicates that the asynchronous process is not yet completed.
  • fulfilled: If the process is successful, the PromiseState is changed to fulfilled state, and the PromiseResult is updated with the data of that process.
  • rejected: If the process is unsuccessful, the PromiseState is changed to rejected state and the PromiseResult is updated with the reason for the failure of the process.

A promise is said to be settled when the value of PromiseState is either "fulfilled" or "rejected"

Ok, this makes sense but as these are internal properties, how do I access the data or error stored in PromiseState? and how do I know when the promise is settled?

To answer this, let's look into the Prototype property of a Promise object

The prototype property of a promise has four functions out of which one is the constructor which we will talk about later. The other functions catch, finally, and then allows us to use the PromiseResult and also keep track of when the promise is settled i.e PromiseState.

image.png

Now to understand how we can use these functions to use Promise in our code, we need to understand how the promise works

How does a promise work?

Let's take the example of fetching data from some server. Here we will be using JSON placeholder API to fetch some users' data.

I'll use Axios to make an API call. Here, axios.get method returns a promise.

const response = axios.get('https://jsonplaceholder.typicode.com/users')

So as we have seen above, a promise object has an internal property Prototype and this has some methods which can be used to get the data from a promise.

  • then: The then method takes two arguments which are functions. The first argument is a success handler. The success handler is called when the PromiseState changes to 'fulfilled' and the value of PromiseState is passed as an argument to the handler function. Similarly, the second argument is an error handler that runs when the PromiseState changes to 'rejected' and receives the value of PromiseState as an argument.
  • catch: The catch method takes one argument which is an error handler function. This function is called when the PromiseState is changed to 'rejected'.
  • finally: The finally method takes a single argument that should be a function. This function is executed when a promise is settled i.e either the promise is fulfilled or rejected.

Now in order to use the data from the JSON placeholder API in our example. we will be making use of these methods.

const response = axios.get('https://jsonplaceholder.typicode.com/users')

//runs when the promise is fulfilled
response.then((data) => console.log(data)) //logs the data received from server

//runs when the promise is rejected
response.catch((error) => console.log(error)) //logs the error due to which promise is rejected

//runs when either the promise is fulfilled or rejected
response.finally(() => console.log('promise is settled'))

Create a promise

Now that you know how a promise works, Let us create our own promise using the Promise constructor

Syntax:

const mypromise = new Promise((resolve, reject) => {
    //do something
})

The Promise() constructor takes an executor function as an argument. The executor function takes two functions as an argument i.e resolve and reject which is passed by javascript internally when the executor function is called.

If the promise returns successfully, the resolve() function is called. And, if an error occurs, the reject() function is called.

You can also call the resolve in the executor function to resolve a promise. The arguments to the resolve method will be the value of PromiseData after the promise is resolved. Similarly, you can call the reject method to reject a promise.

I hope this post was informative. Feel free to comment or reach out to me if you have any questions.