JavaScript’s Promise Object

Pluto
3 min readJun 26, 2021

--

1. A Promise in JavaScript

What is a promise?

A promise is the JavaScript object that represents the completion or failure of an asynchronous operation and its resulting value.

How does it work?

The idea of a promise is the object which can be in a certain state. The initial state is ‘pending’ where the promise is waiting for the asynchronous operation to finish. When the operation is successfully resolved, the promise is going to be ‘fulfilled’ state while when some errors happen during the operation, it is going to be a ‘rejected’ state.

In order to get the actual result / error value from the promise, we need to use .then() and .catch() functions. .then() is the function which is executed when the promise has been fulfilled while .catch() function is executed when the promise has been rejected.

.then() takes up to two-argument, a callback function for the resolved case and the second argument is the callback function for the rejected case. Both callbacks will eventually return a new promise object which can be used for further associate actions by chaining.

thisIsPromise
.then(callbackForResolvedA, callbackForRejectedA)
.then(callbackForResolvedB, callbackForRejectedB)
.then(callbackForResolvedC, callbackForRejectedC)

The rejected promise can be handled immediately in each .then() like the example above. But if the immediate error is not needed, then the error can be handled with .catch() function at the end of the chain.

thisIsPromise
.then(callbackForResolvedA)
.then(callbackForResolvedB)
.then(callbackForResolvedC)
.catch(callbackForRejected)

The diagram below shows how the status of the promise changes over time (from MDN).

MDN(https://mzl.la/3pQtZvP)

3. Code examples & real-world use case

Code examples

Let’s look at some code examples to show how to use promises in actual codes.

Real-world example

One of the real-world examples of using promises is making a request for an API. In this article, let’s make a request to Poke API to get the names of pokemon! *Poke API is the REST API where we can get various kinds of pokemon data (they have announced Beta support for GraphQL) https://pokeapi.co/

In the example, I will use ‘fetch’ (native Javascript method) to send a request to the API. The fetch method returns a response as a promise. Since the response from fetch is not JSON but an HTTP response, the response has to be converted into JSON by json() to actually extract data from JSON body content. In addition, the json() function is also returns a promise, I have to use .then() after the conversion.

This is going to give us one pokemon object that contains the following information:

  • count
  • next
  • previous
  • results
  • name
  • url

If we need only the name from this data, we can just simply specify data.name after converting it into the JSON.

fetch('<https://pokeapi.co/api/v2/pokemon/?limit=1>')
// Convert the response to JSON
.then(response => response.json())
// json() returns a promise, so need .then() here
// if we need only name, then write (data.name)
.then(data => console.log(data))

// Handling error
.catch(err => console.log(err))
//Result
/*{
count: 1118,
next: "<https://pokeapi.co/api/v2/pokemon/?offset=1&limit=1>",
previous: null,
results: {[
name: "bulbasaur",
url: "<https://pokeapi.co/api/v2/pokemon/1/>"
}]
}
*/

The example above shows the sending only one request. But it is often required to make another request with the result from the first request. Now let’s look at the example of sending multiple requests.

In the previous example, we get only the basic information, but Poke API has more details for each pokemon. In order to get details, we need to send another request with the URL that is in the results object in the previous result.

//Result
/*{
count: 1118,
next: "<https://pokeapi.co/api/v2/pokemon/?offset=1&limit=1>",
previous: null,
// We need this!!!!!!!!
results: {[
name: "bulbasaur",
url: "<https://pokeapi.co/api/v2/pokemon/1/>"
}]
}
*/

In the example below, we get the weight data from the second request.

fetch('<https://pokeapi.co/api/v2/pokemon/?limit=1>')
.then(response => response.json())
.then(data => fetch(`${data.results[0].url}`))
.then(response => response.json())
.then(details => console.log(details.weight))
// Handling error
.catch(err => console.log(err))
//Result
//69

4. Conclusion

A promise is one of the ways to handle asynchronous operations in JavaScript. I hope I could illustrate what is a promise and how to actually use it in the code.

If you found this article helpful, please click the clap button, you can also follow me on Twitter if you have any doubt, feel free to comment! My GitHub account: pluto004

--

--

Pluto

Studying at Codechrysalis. Marketing researcher before.