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.

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.

Definition of promise -Google
  1. After a promise is made, we get an assurance about ‘something’ and we can plan accordingly.
  2. They can be kept or broken.
  3. 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-

  1. Creation of Promises
  2. 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-

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

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

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.

Credit @Medium

0
Would love your thoughts, please comment.x
()
x