JavaScript Promises

Mustafa Ozdemir
Analytics Vidhya
Published in
3 min readOct 4, 2020

In today’s blog, we are going to be talking about promises in JavaScript. Before all those explosions and syntax, I just would like to give you some backstory to our main character in this post to make you care about logic behind the promises, not the boring syntax. This post is going to be a character-driven, not a plot-driven blog. Sit back, grab your popcorn and enjoy the blog.

A promise in JavaScript is just like a promise in real life. You promise something and it has two results either the promise has completed or it has failed. In Java Script, a promise function gets two parameters which are resolve and reject.

A Promise is in one of these states:

  • pending: initial state, neither fulfilled nor rejected.
  • fulfilled: meaning that the operation was completed successfully.
  • rejected: meaning that the operation failed.

Let’s look at the actual syntax of creating a promise.

var promise = new Promise( function(resolve, reject) {
/* Promise content */
})

As it might be seen, a promise constructor takes one parameter which is a function that passes two variables called resolve and reject. That code is going to return two possible results. If the promise is fulfilled then the resolve method will fire. If things goes wrong and the promise is going to fire the reject method to allow us to handle the error.

Chain promises

When it comes to promises in JavaScript .then() and .catch() blocks are very handy methods to use. We can chain our promises with the .then() method and only use one .catch() method end of the chain to handle our all exceptions may occur during one of the then() tasks executions.

Let’s put together everything we have mentioned above.

fetch(‘https://ergast.com/api/f1/2004.json’)
.then(res => res.json())
.then(data => data.MRData)
.then(element => {
console.log(element);
})
.catch(error=>{
console.error(error);
});

In this code sample, we fetch a JSON data from an API which is provided by ergast.com and chain the data with then() methods and to handle the possible exceptions we passed a catch() block end of the then() chain. Now, we have very simple and readable code.

That's all for this post. Hope you enjoyed it.

References

--

--