Promises in ES6

Like Tweet Pin it Share Share Email
Promises in ES6

Hello, web programmers, In today’s AppDividend Tutorial, I have briefly described Promises in ES6.

Promises have arrived natively in ES6. It is also available in 3rd party libraries like fetch which is used in HTTP calls or AJAX calls, and also jQuery 3.0 now supports Promises.

What is Promise

As its name suggests, It will return a promise as an object of any particular asynchronous actions. Promises are results of eventual operations, and it is Object. This object has three states.

  1. Pending State
  2. Fulfilled State
  3. Rejected State

I will explain you one by one state but first, let me tell you its syntax

Syntax

let promise = new Promise((resolve, reject) =>  {
        // here async actions are performed
        resolve('your result');
});

// in case of success
promise.then((resolve) => console.log(resolve));

//in case of fail or an error
promise.catch((reject) => console.log(reject));

In promise, we have to pass two arguments to its constructor

  1. resolve
  2. reject

At this point, we do not know whether the promise will resolve or reject because in asynchronous calls will take some milliseconds to execute the promises. Asynchronous calls are simply AJAX calls, which will take some time to execute and will get a response from the server. So by that time, the state will be pending.

Pending State

While the Asynchronous task is performed, the promise object is in the holding state which does not contain any value. Instead, it will return a promise that any point of time in future it will get either resolve or reject with any error. This state is called Pending state

Resolve or Fulfilled State

If the operation of the Asynchronous task is successfully completed, then It will be resolved, and you can get its value by calling then function on promise object.

//main.js

let promise = new Promise((resolve, reject) =>  {
        setTimeout(() => {
            resolve('Promises are working')
        }, 2000);
});
promise.then((data) => {
    console.log(data);
});

Possible Errors

  1. If you perform code directly in your browser, then chances are very high to fail the webpack compilation process.

Possible Solutions

  1.  Beginner’s Guide To Setup ES6 Development Environment  Follow this article strictly and put above code in the main.js file.

Output

let promise = new Promise((resolve, reject) =>  {
        setTimeout(() => {
            reject('Aww there is something wrong')
        }, 2000);
});
promise.catch((error) => {
    console.log(error);
});

In this scenario, an Asynchronous task will give an error, and we can call catch method on promise object and take an argument as an error and log that error.

Output

//main.js

let mj = 'KingOfPop';
let prom = (data, callbackFunction) => {
    callbackFunction(null,data);
}
prom(mj, (error, data) => {
    console.log(data);
    prom(mj, (error, data) => {
        console.log(data);
        prom(mj, (error, data) => {
            console.log(data);
        });
    });
});

Output

//main.js

let prom = (data) => {
    return new Promise((resolve, reject) => {
        if(data){
            resolve(data)
        }
        reject('An Error occured');
    });
}
Promise.all([
    prom('KingOfPop'),
    prom('KingOfPop'),
    prom('KingOfPop')
]). then(data => data.forEach(d => console.log(d)));

KingofPop
KingOfPop
KingofPop

So, basically, we can compose multiple promises and then it will resolve or reject depending on the result. It is very cool. In above examples, I have not used Asynchronous Code because I am leaving it to you to perform faking ajax request or use timeout function on your own and see the magic.

Promises In ES6
Promises In ES6

Memorable Points

  1. Promises are a way of saying that till now I have not any data while in a pending state, but in future, It will surely either resolve or reject the data depending on the result.
  2. We can use multiple promises and compose it in a way that we can remove a callback hell problem.
If you still have doubt then ask in the comment below, I am happy to help you out.

Comments (1)

Leave a Reply

Your email address will not be published. Required fields are marked *