Promises in ES6

Promises in ES6

A promise is used to represent some aspects that are finally fulfilled. It can also be resolved or discarded according to the operational output. In ES6, a promise provides a way to handle asynchronous programming. The promise is also used in JavaScript. The asynchronous programming consists of the processes that are in the execution phase, separated from the main thread. When the process is completed, then it notifies the main thread. Before the concept of promise, the callback functions were responsible for asynchronous programming.

Callback Function

The callback function can be defined as the function execution handler. It handles the function execution after the execution of any other function. We can pass a function as an argument to the other function. The callback function is also used with events.

Need of Promises

The Callback function is suitable for the basic asynchronous operations in programming. If we talk about web application development, then Callback is complicated to handle, because a web application has a huge code. The situation of Callback nesting is called as Callback hell. We can deal with this kind of situation with the help of promises.

Working with Promises

Usually, the promise shows the accomplishment of an asynchronous operation in programming. The promises return the single value according to the operation being executed or discarded.

The promise contains the following three phases, shown in the below figure.

Pending Phase: It is the initial phase of the promise. It shows that the output of a promise is computed or not.

Fulfilled: This phase represents that the operation has executed.

Rejected: This phase is used to represent the decline of the execution.

When a promise is being discarded or executed, then it becomes immutable. A promise() constructor obtains resolve or reject arguments, and return the single argument according to the asynchronous operation.

Creating the promise

The promise() constructor is used to construct a promise in ES6. The syntax for creating the promise is given below.

Syntax

const Promise = new Promise ((resolve, reject) => {…});

Example

Here, we have an example of a promise.

let Promise = new Promise((resolve, reject)=>
{  
          let p = 5;  
          if(p ==5)
{  
        resolve('Executed');  
 }  
    Else
{  
        reject('Rejected');  
 }
})  
Promise.then((message)=>
{  
            console.log("It is a then block. The message is: ?+ message)  
}).catch((message)=>
{  
console.log("It is a Catch block. The message is: ?+ message)  
})  

Output

After the execution of the above code, we got the following output:

Promise Chaining in ES6

In JavaScript, the promise chaining helps us to control the flow of the asynchronous operations. It also enables us to use a returned value as an input for the other asynchronous operation.

For Example

Assume, if we have multiple asynchronous operations for execution. When one operation generates the output, then we will switch to another operation for execution. The promise chaining helps us to handle various asynchronous operations that are interdependent, and each function should be executed one by one.

Here, we have an example to understand the above concept.

Example

<!DOCTYPE html> 
<html lang="en"> 
<head> 
    <meta charset="UTF-8"> 
    <meta name="viewport" content="width=device-width, initial-scale=1.0"> 
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title> 
</head> 
<body> 
    <script> 
        const PromiseP = () =>{ 
            return new Promise((resolve,reject)=>{ 
                resolve("Hello Promoise P"); 
            }); 
        }
        const PromiseQ = () =>{ 
            return new Promise((resolve,reject)=>{ 
                resolve("Hello Promise Q"); 
            }); 
        }
        const PromiseR = () =>{ 
            return new Promise((resolve,reject)=>{ 
                resolve("Hello Promise R"); 
            }); 
        } 
        PromiseP().then((P)=>{ 
                  console.log(P); 
                    return PromiseQ(); 
                }).then((Q)=>{ 
                    console.log(Q); 
                    return PromiseR(); 
                }).then((R)=>{ 
                    console.log(R); 
                });        
     </script> 
</body> 
</html> 

Output

After the execution of the code, we can open the console terminal by using ctrl+shift+I, and we got the following output:

Method of Promise

The promise method helps us to deal with the resolution or rejection of the promise object. Here, we discuss the promise methods in detail.

.then() method

This method gets invoked at the time of execution or rejection of a promise. The .then() method can be defined as a chained way to execute or reject the promise. We can pass two arguments in the method, such as reject or resolve. This method returns the first argument if the promise is rejected, and second if the promise gets executed.

Example

Here, we have an example to understand the above method.

let success = (p) =>
{
          console.log(p + “It executed!”)
}
let error = (p) =>
{
          console.log(p + “It failed!”)
}
const promise = number =>
{
          return new promise((resolve, reject) =>
{
          if((number%2)= = 0)
{
          resolve(“Successful!”);
}
reject(“Failure!”)
})      
}
promise(50).then(successful, error)
promise(17).then(successful, error)

Output

After the execution of the above code, we got the following output:

.all() method

This obtains a promise array as an argument. It returns a resolved promise that executes if all the promises are passed as an iterable that have being executed.

Example

Here, we discussed an example for the above method.

const PromiseX = Promise.resolve(“Hello”);
const PromiseY = ‘ES6’;
const PromiseZ = new Promise(function(resolve, reject))
{
          setTimeout(rsolve, 10, 100);
});
Promise.all([PromiseX, PromiseY, PromiseZ]).then(function(values)
{
          console.log(values);
});

Output

After the execution of the above code, we got the following output:

.race() method

This method returns a resolved promise which depends upon the previously resolved promise.

Example

Here, we have an example to understand .race() method.

const pro1 = new Promise(resolve, reject) =>
{
          setTimeout(resolve(“Pro1 is the first Promise”), 100)
})
const pro2 = new Promise(resolve, reject) =>
{
          setTimeout(resolve(“Pro2 is the second Promise”), 200)
})
Promise.race([Pro1, Pro2]).then (output =>
{
          console.log(output);
})

Output

We got the following output after the execution of the above code.

.catch() method

The .catch () method is used to deal with rejections and failures. This method obtains only single arguments to deal with failures.

Example

Here, we discussed an example of the above method.

const Promise = number =>
{
          return new Promise((resolve, reject) =>
{
          if (number > 0)
{
          resolve(“Successful”);
}
          reject(“Failure”);
})
}
Promise(10).then(result =>
{
          throw new Error();
console.log(result + “Successful!”)
}).catch(error =>
{
          console.log(error + “It Failed”)
})

Output

After the execution of the above code, we got the following output:

.resolve() method

The .resolve() method returns a new promise object, resolved by the passed value. If the value includes .then() method, then the promise pursue .then() method.

Example

Promise.resolve(‘successful’).then(function(value)
{
          console.log(value);
}, function(value)
{
});

.reject() method

This method returns the promise object which is rejected with the given value.

Example

Here, we discussed an example of .reject() method.

function resolved(output)
{
          console.log(“Resolved”);
}
function rejected(output)
{
          console.error(output);
}
Promise.reject(new Error(‘Failed’)).then(resolve, rejected);

Output

After the successful execution of the above code, we got the following output: