Learn Promises in JavaScript | ECMAScript

By : FiveMinute  |  Updated On : 01 Mar, 2021

Learn Promises in JavaScript | ECMAScript

Promises in JavaScript helps us to write asynchronous code. There are other ways also to write async code like callbacks but when we have lots of callback to handle it goes to callback hell and very tough to manage the code. We use promises to looks code simple and easy understandable. Here I will explain how promises work as simple as I can.

What is a Promise?

JavaScript promise is same as the real life promise, when someone gives you promise it confirms that He/She will do something in the future and in return it get success or failure. In the same way JavaScript promise works when you declare a promise it has a callback function with 2 parametes resolve and reject. When promise get succes it calls resolve and if fails it calls reject. When resolve called then method is called or if reject called than it goes to catch block to handle the error as given in the below example.

function sendRequest(talkTo) {
    return new Promise((resolve, reject) => {
        if (talkTo == "Google") {
            resolve("Hi, You are talking to google");
        } else {
            reject("Sorry! You can only talk to google");
        }
    })
}

Here we created a function sendRequest which have a parameter on the basis of that parameter we decide to call the resolve or reject and returning a promise. 

Now call the sendRequest method with Google parameter and check the output.

sendRequest("Google").then(response => {
    console.log(response);
})

Output : 

Hi, You are talking to google

Next, call the same sendRequest method with Facebook which is wrong parameter and check the output.

sendRequest("Facebook").then(response => {
    console.log(response);
})

Output :

Uncaught (in promise) Sorry! You can only talk to google

when we send request with Facebook, We got uncaught error because we didn't handle the error yet. To fix this we need to handle the error with catch block like below.

sendRequest("Facebook").then(response => {
    console.log(response);
}).catch(error => {
    console.log(error);
})

Output

Sorry! You can only talk to google

Now we handle the error in catch block and console the error received from the promise rejection.

 

Sometimes we create a normal function but we need the normal function return promise instead of normal value. To achive this there are two methods Promise.resolve and Promise.reject from the promise object. You can look the below example to understand easily.

Promise.resolve()

Promise.resolve method from the Promise object. It returns with promise to handle it with then method. It doesn't return with reject as we are resolving some value on it. Look below example.

function getData() {
    return Promise.resolve(12345);
}

The above function getData returning Promise object which is handle by then method like below.

getData().then(data => {
    console.log(data);
})

//Output
12345

 

Promise.reject()

Promise.reject method from the Promise object. It returns with promise to handle it with catch method. It doesn't return with then as we are rejecting some value(error) on it. Look below example.

function getData() {
    return Promise.reject("something wrong");
}

The above function getData returning Promise object which is handle by then method like below.

getData().catch(data => {
    console.log(data);
})

//Output
something wrong

Implementing both in single function on conditional basis to understand more.

function getData(param) {
    if (param == "Google") {
        return Promise.resolve("Hi I am a google");
    } else {
        return Promise.reject("Sorry we can only talk to google");
    }
}

Next call getData function with google parameter.

getData("Google").then(data => {
    console.log(data);
}).catch(error => {
    console.log(error);
})
//Output
Hi I am a google

Next call the function with wrong parameter.

getData("Facebook").then(data => {
    console.log(data);
}).catch(error => {
    console.log(error);
})
//Output
Sorry we can only talk to Google

 

Promise.all

Promises.all is a promise which takes number of arrays as promise and called then chaning method when all promises get resolved or any one of the promise get rejected. It calls all the promises in parallely which saves time. Below are the example of promise.all

const promise1 = new Promise((resolve, reject) => {
    resolve('promise1 data');
});

const promise2 = new Promise((resolve, reject) => {
    resolve('promise2 data');
});

Promise.all([promise1, promise2]).then(response => {
    console.log(response);
}).catch(error => {
    console.log(error);
})

Here we create 2 promises which is passed in promise.all with in array and called the then chaining method to get response of both promises. 

Output :

[ 'promise1 data', 'promise2 data' ]

In the above output you can see the result given in array when both the promises get resolved. We can get value by indexing like below.

Promise.all([promise1, promise2]).then(response => {
    console.log(response[0]);
    //response[0] - it is the response from promise1

    console.log(response[1]);
    //response[1] - it is the response from promise2

}).catch(error => {
    console.log(error);
})

To learn Async Await - Click Here