ES6 Promises
Tags: beginners, tutorial, javascript, webdev
Published: 2020-01-15 18:11:59


Some of the features to learn in ES6 are Promises, async-await, destructuring and more.

Here In this blog, we can explore the ES6 Promises and more details about them.

Before to get into the Promises, we need to examine the difference between asynchronous and synchronous.


Generally, when we compile the code it compiles with JIT Compiler and Intrepretes the code line after the line and continues till the end of the file.
The execution of the code happens with-in Interpreter each line.
Such execution is called synchronous.
Synchronous:
```javascript
            fun()
          {
            console.log('Hello World1');
            console.log('Hello World2');
            console.log('Hello World3');
          }

          fun();
```

Line2 doesn't execute till the completion of the line1, and same goes with the line3. The execution start time of a new line will be after the completion of the old line.


**Point to remember: JavaScript is used in the Web apps and in which communication between the Client and Server happens**


It may not seem to have any problem with such the execution, but while the communication between server and client is done with the JavaScript execution, If any of the JS code executes for a long time till then the other part of the file has to wait for the completion of the execution. if it happens to take a long time(for suppose to be 10min or more), till then the other part has to hang on. Here the problem arises. Such problems can be resolved with the asynchronous execution type.

```javascript
             fun()
             {
                setTimeout(function fun1()
                              {
                                console.log('Hello from function');
                              },2000);
                 console.log('Hello fromoutside fun');
             }

             fun();

```
***Things to notice from above code:***

  1. function fun1 is passed as a parameter to the setTimeout function(It's not a function call but a function definition itself)
  
  2. setTimeout is an in-built function which executes the passed function parameter after n seconds, where n value is passed as the second parameter to the setTimeout.
  3. It's a basic and general one to consider setTimeout as an asynchronous as it takes executes after a few seconds. Here we are using the setTimeout function for the simulation of the asynchronous type of code.
 
 let us consider one example for more explanation

```javascript

     myvar=100;
     console.log('Before function Myvar:'+myvar);
     setTimeout(()=>{
          myvar=myvar/2;
           },2000);
     console.log('After function Myvar:'+myvar);
```
***Output***
You may expect the output would be to print the value of myvar value as 100 and 50 respectively.
But when you run it in v8 console you would get the output as below

![Alt Text](https://thepracticaldev.s3.amazonaws.com/i/bacanejgr7zw8k43peap.png)

In order to print the Myvar value as 100 and 50 respectively after the first and second console of the variable, we need to make use of ES6 features

It(Asynchronous code execution) can be achieved through 
 
  a. function callbacks,
  b. Promises,
  c. async-await functions.


Here we will look at details about the Promises.

Promises are in-built objects, which are instantiated with the Promise constructor. The Promise constructor takes a function as a parameter.
Promise objects have three states in any of the execution:
Three of the Promise states are: 
                                 a. Pending state,
                                 b. Resolved state,
                                 c. Rejected state.

Whenever we want to execute the asynchronous code we will wrap such block in the Promise and write it so we can achieve what we require. In order to make it we instantiate an object with Promise constructor and use the object for further computing. Promise constructor has a function parameter. so we need to pass it in the call.

```javascript
p = Promise(function);
````
This is how we need to instantiate the Promises. At the instantiation level, all the promises would be a pending state. Now we need to include the asynchronous code in the function parameter. Thus we will look at the implementation of it. Based upon the Implementation of the promise it would resolve  Also, that parametric function also has again two function parameters. By convention, these two functions are named as resolve and reject.

````javascript
p = Promise(function(resolve,reject){
                   //Asynchronous code block
});

```
In the function parameter after the asynchronous code Implementation, the promise needs to be resolved into a rejected state or fulfilled state upon the success or failure of the promise.

For further computation based on the results of the Promise states, we can proceed with the then or catch functions.

Example scenario: If the asynchronous code is Implemented and the promise reaches the fulfilled state. Hence the result can be taken in the then method of the promise instance.

***Consuming Promises***

```javascript
myvar=100;
console.log('Myvar before function:'+myvar); 
p = new Promise(function(resolve,reject)
                {
                   setTimeout(()=>{
                                    myvar=myvar/2;
                                    resolve(myvar);  
                                   },2000);
                                 //promise is fulfilled with resolve call
                });
p.then((result)=>{
console.log('Myvar after function:'+result);
});
})
```

'Then' method has an extra second parameter where the error of the resolved promise can be handled. resolve and reject can pass a string, variable, array or of any other data types. Here we are passing the numerical variable whose value we need it in future circumstances.

But if the asynchronous code implementation is deduced that it leads to rejected state from the Pending state. Then the resultant compilation would not go to the resolve function but to the catch promise method.

```javascript
password='mypassword';

p = new Promise(function(resolve,reject)
{
             //Async code block
              if(password == 'mypassword')
               resolve();
              else
              reject();
});

p.then((result)=>{
          console.log('Valid Password');
});
```

```javascript
password='password';

p = new Promise(function(reslove,reject)
{
             //Async code block
              if(password == 'mypassword')
               resolve();
              else
              reject();
});

p.then((result)=>{
          console.log('Valid Password');
});

p.catch((error) => {
          console.log('Invalid Password:Error');
});
```

 As the promise is rejected, it is handled with the catch method.

Promise Object after asynchronous implementation will return the Promise object again.which is resolved/rejected.

But if you want the any implementation to be resolved at a particular instance then it can be done with the resolve method.

***Creating settled Promises***


```javascript
p = Promise.resolve(3);

p.then((value)=>{
     console.log('value:'+value);
});
```

The above code prints the numerical value 3.
so we need to pass the function for the direct transfer of a promise to resolved state. We can make it upon the function call. Note that we didn't create promise object here with new keyword but we directly called the resolve method on the promise constructor. And as stated earlier resolve method returns the Promise but fulfilled state which can be handled in 'then' method. 

same can be done with the reject method if one wants to reject the promise object with the rejected state. While the rejected state can be handled with the catch method.

```javascript
p = Promise.reject(3);

p.catch((value)=>{
     console.log('Rejected value:'+value);
});
```

***Chaining of Promises***
As the fulfilment of the promise to resolved state or rejected state, we consumed them separately upon the Promise object with then and catch method calls. But they can also be chained. 
Considering the above example again here.

```javascript

password='password';

p = new Promise(function(reslove,reject)
{
             //Async code block
              if(password == 'mypassword')
               resolve();
              else
              reject();
});

p.then((result)=>{
          console.log('Valid Password');
}).catch((error) => {
          console.log('Invalid Password:Error');
});

```

Note that the promise methods are defined on the same promise object 'p'. Whereas before it was defined separately on p. Such a methodology is called chaining of promises.

Interested can check for:

Promise.all, and various other Promise methods.
callback functions and call back hell problem
async-await functions.