Promises in Javascript

Promises in Javascript

JavaScript 11-08-2021 Saheb Sutradhar

Promises in Javascript

 

what are promises in javascript ?

Promises in javascript is like promises in real life . It’s like you are promising your parent that in one month you will completely learn javascript , So by end of the month you can successfully finish your promise or you can fail .

In Javascript we use promise to handle asynchronous operation . Promises are easy to manage, when you have multiple asynchronous operations and to handle them if you use callbacks that can lead to unmanageable code which is know as callback hell.

 

let’s check the simple promise example

let promiseToLearnJavaScript = new Promise((resolve, reject) => {

    let isJavaScriptCompleted = true;

    if (isJavaScriptCompleted) {
        resolve("Successfully learned Javascript");
    }
    else {
        reject('Failed to learn Javascript');
    }

})

promiseToLearnJavaScript.then(result => {
    console.log(result);
}).catch(error => {
    console.log(error.message)
})

Promise takes a callback function as parameter ,and the callback function has two arguments one in resolve and another is reject .These two arguments are function  , We call the resolve function when the task in successful and we call the reject function when the task is failed .

Now when we executes the promise , then() gets called when the promise is resolved . then function takes a callback function as argument , and the callback function has an argument which gives us the result or data which we are passing as parameter of the resolve function .

And if the promise rejects then catch method gets executed . catch method takes a callback function as argument  and the callback function has an argument which gives us the result or data which we are passing as parameter of the reject function .

Note : While executing promise you always should handle the promise Rejection by declaring catch method , else you will be getting below warning message .

(node:75559) UnhandledPromiseRejectionWarning: Failed to learn Javascript

 

Let’s see an example where one promise is depending on another promise.

promise chaining in javascript

let learnBasicJS = function(){
    return new Promise((resolve,reject)=>{
        resolve("Learned Basic")
    })
}

let learnAdvanceJS = function(){
    return new Promise((resolve,reject)=>{
        resolve("Learned Advance")
    })
}

learnBasicJS().then(result=>{
    return learnAdvanceJS()
}).then(result=>{
    console.log(result);
})

 

in the above example we have two variables and in both the variables we have stored functions which return Promise. so when we are executing the learnBasicJS() method it return a promise and we have used then() method to handle that promise.

If the learnBasicJS promise is resolved then we are executing the learnAdvanceJS() method and returning the learnAdvanceJS promise .

To handle the learnAdvanceJS promise again we called then() method . This way to handle the promises called promise chaining in javascript.

 

Below example we will see how we can execute promise based on data and how to handle promise rejection in single place.

 

let learnBasicJS = function(status){
    return new Promise((resolve,reject)=>{
        if(status){
            resolve(true)
        }
        else{
            reject(false)
        }
    })
}

let learnAdvanceJS = function(status){
    return new Promise((resolve,reject)=>{
        if(status){
            resolve(true)
        }
        else{
            reject(false)
        }
    })
}

learnBasicJS(true).then(result=>{
    return learnAdvanceJS(result)
}).then(result=>{
    console.log("Congratulation you have reached till Advance Javascript");
}).catch(error=>{
    console.log('You are failed to learn Javascript')
})

 

promise.all in javascript

all() method takes the array of promises as argument , when all the promises are fulfilled  then it returns a promise. If that promise if fulfilled then executes then() method, if the promise rejects then the catch() method gets executed .

Suppose you have a requirement  where you have to send message and email to the customer . If sending message and email are successful then the complete process is done , if any of them fails the complete process fails. Check the below code.

 

let sendMessageToCustomer = function () {
    return new Promise((resolve, reejct) => {
        let status = true;
        if (status) {
            resolve("Message Sent")
        } else {
            reejct(new Error("Failed To send the message"))
        }
    })
}

let sendEmailToCustomer = function () {
    return new Promise((resolve, reejct) => {
        let status = true;
        if (status) {
            resolve("Email Sent")
        } else {
            reejct(new Error("Failed To send the Email"))
        }
    })
}

Promise.all([sendMessageToCustomer(), sendEmailToCustomer()]).then(result => {
    console.log("Process Completed")
}).catch(error => {
    console.log(error.message);
    console.log("Complete Process Failed")
})

 

Promise.race in Javascript

race() method takes the array of promises as argument. Promise.race() method returns Promise that promise fulfills or reject when any of the promise in the promise array fullfills or rejects . 

In the below example there are three tasks of any of the task is completed then the process is completed if any of the task is failed then the complete process is failed.

let task1 = function () {
    return new Promise((resolve, reejct) => {
        let status = true;
        if (status) {
            resolve(true)
        } else {
            reejct(false)
        }
    })
}

let task2 = function () {
    return new Promise((resolve, reejct) => {
        let status = true;
        if (status) {
            resolve(true)
        } else {
            reejct(false)
        }
    })
}

let task3 = function () {
    return new Promise((resolve, reejct) => {
        let status = false;
        if (status) {
            resolve(true)
        } else {
            reejct(false)
        }
    })
}

Promise.race([task1(), task2() , task3()]).then(result => {
    console.log("Process Completed")
}).catch(error => {
    console.log("Complete Process Failed")
})

 

 

I hope this article is helpful for you , i am very glad to help you thanks for reading

 

Related Posts

Card image cap

Math Floor Javascript Method

JavaScript 16-07-2021 Saheb Sutradhar

math.floor javascript method takes a number type value as parameter and returns the round off of that value. The return value will be the nearest downward integ ...

Card image cap

Spread Operator in JavaScript

JavaScript 20-07-2021 Saheb Sutradhar

In this post we will learn what is spread operator in Javascript? How we can use it ? and Where we should use? Spread Operator allows you to spread out the ele ...

Card image cap

Remove duplicates from array in javascript

JavaScript 24-07-2021 Saheb Sutradhar

In this post i will show you how to remove duplicates from array in javascript.We can use filter() method to remove duplicates from array , if the index of the ...

Card image cap

Next and Previous Buttons in Javascript with Demo

JavaScript 27-07-2021 Saheb Sutradhar

In this post we will learn how to use next and previous buttons in javascript with demo application , the below example there is  image container and next, pre ...

Card image cap

Image size validation in javascript example

JavaScript 28-07-2021 Saheb Sutradhar

In this article you will learn Image size validation in javascript with example , along with the size validation you will learn how to validate image mime type. ...

Card image cap

How to get multiple checkbox value in javascript

JavaScript 30-07-2021 Saheb Sutradhar

In this post you will learn how to get multiple checkbox value in javascript . In many application you will find this kind of feature where we allow user to sel ...