Codementor Events

Truly understanding Promises in JavaScript

Published Jan 07, 2019Last updated Jul 05, 2019
Truly understanding Promises in JavaScript
                         ## Photo by rawpixel on Unsplash## 

Share this article on LinkedIn!
Original article on medium
Click here to share this post on Linkedin!
Almost anyone who has used JavaScript, had a love/hate relationship with it at some point. JavaScript is like that girlfriend who is frustrating at times but has something about her which keeps us intrigued. JavaScript has a galore of interesting topics and concepts to explore. Let’s start with one of them- Promises.

Just like no Spider-man movie is complete without the dialogue With great power comes great responsibility
No article based on Promise is complete without stating that Promises save you from callback hell.

But there is more to promises and I will be showing that to you.

JavaScript is a synchronous programming language, but because of callback functions we can make it work like an Asynchronous Programming language.

Promises
Promises in javascript are very similar to promises made in real life.

1_UcJSj8vyeAB_zgojmACsKw.png
Definition of promise -Google
After a promise is made, we get an assurance about ‘something’ and we can plan accordingly.
They can be kept or broken.
We can’t act on them immediately. Only after the promise is kept.
According to MDN:

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

Playing with promises has 2 parts-

Creation of Promises
Handling of Promises

Creation
Promises have the basic blueprint

new Promise( /* executor */ function(resolve, reject) { ... } );
                                                               --MDN

The executing function(executor) accepts two parameters resolve and reject which in turn are callback functions. Promises are used for handling asynchronous operations also called blocking code, examples of which are DB, I/O or API calls, which are carried out by the executor function. Once that completes it either calls resolve on success or reject function on error.

Simple example

let promise = new Promise(function(resolve, reject) {
if(promise_kept)
  resolve("done");
else
  reject(new Error("…"));
  
});

As it can be seen, Promises don’t return values immediately. It waits for the success or failure and then returns accordingly. This lets asynchronous methods return values like synchronous ones. Instead of returning values right away, async methods supply a promise to return the value.

The above paragraph makes one thing clear, It has states!

A promise can be one of these states-

pending — This is the initial state or state during execution of promise. Neither fulfilled nor rejected.
fulfilled — Promise was successful.
rejected — Promise failed.

The states are quite self-explanatory so won’t go in detail. Here is a screenshot for reference.
1_JaE8Vjaa4J3GF50xHl8B5A.png

Handling and Consuming the Promise
In the last section we saw how Promises are created, now let’s see how the promise can be consumed.

const isDone = new Promise()
//...

const checkIfDone = () => {
  isDone
    .then(ok => {
      console.log(ok)
    })
    .catch(err => {
      console.error(error)
    })
}

Running .checkIfDone() will execute the isDone() promise and will wait for it to resolve, using the then callback. If there is an error it will be handled in the catch block.

Chaining Promises
A promise can be returned to another promise , creating a chain of promises. If one fails all others too. Chaining is very powerful combined with Promise as it gives us the control of the order of events in our code.

new Promise(function(resolve, reject) {

  setTimeout(() => resolve(1), 1000); 

}).then(function(result) { 

  alert(result); 
  return result * 3;

}).then(function(result) { 

  alert(result); 
  return result * 4;

}).then(function(result) {

  alert(result); 
  return result * 6;

});

All of the operations return there results to the next then() function on resolve and this process continues till the chain is complete. The last element in the chain return the final result.

Conclusion
This was just a basic gist of JavaScript promises. Promises can do a lot more if used in the right way and the right place.
Hope you enjoyed reading. Follow me on Twitter && Medium
Original article on medium

👏👏👏👏👏👏👏

Discover and read more posts from Ashay Mandwarya
get started
post commentsBe the first to share your opinion
Brian Quinn
5 years ago

Nice article.

Patrick Milam
5 years ago

Thanks for taking the time to write this article. I feel you explained the Promise well and made it easy to understand. One thing I struggled with early-on and what I continue to see confusion on is chaining. I feel it would be helpful to see some additional in-depth examples as well as detailed explanations and best practices when using chaining (e.g. what should and shouldn’t be returned from a ‘then’ function and when and when NOT to use chaining). Kudos!

Show more replies