Advance JavaScript

JavaScript – Promise


In JavaScript, a promise is an object that returns a value which you hope to receive in the future, but not now.

Promise in JavaScript very similar to promise done by human beings in daily life. When we do promise with someone. It is a guarantee that we are going to do something in the future. But promises can have two outcomes: Either it is fulfilled in the future or failed. There is also a similar kind of things happens in JavaScript promise object.

Promise in JavaScript comprises of three states:

Pending: Initial state, when promise made and waiting promise to succeed or fail.

Resolved: Promise completed.

Rejected: Promise failed.

For example: If someone request some data from the server, a promise is there to return. It will be in pending mode until the server is processing to respond.

If user gets the data, promise resolved successfully. But if the user didn’t get any data from the server, then Promise will be in the rejected state.

Creating a promise: the Promise constructor

In order to create a promise constructor in JavaScript, we user the promise constructor. The promise constructor accepts a function as argument. This function is called executor. And this function as said above will have two callback functions, resolve() and reject().

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Advance JavaScript - Promise</title>

    <script>
        let complete = true;

        let prom = new Promise(function(resolve, reject){
            if(complete){
                resolve('Success');
            }else{
                reject('Failed');
            }
        });

        console.log(prom)
    </script>
</head>
<body></body>
</html>

In the above example, if complete status is true, then promise will be successful. But if complete status is false, then it will throw an error: Uncaught (in promise) Failed.

We can write promise in this way given below:

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Advance JavaScript - Promise</title>

    <script>
        function prom(complete){
            return prom = new Promise(function(resolve, reject){
                if(complete){
                    resolve('Success');
                }else{
                    reject('Failed');
                }
            });
        }

        console.log(prom(true))
    </script>
</head>
<body></body>
</html>
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Advance JavaScript - Promise</title>

    <script>
        function prom(complete){
            return new Promise(function(resolve, reject){
                console.log("Fetching Date, Please Wait...");

                setTimeout(() => {
                    if(complete){
                        resolve('Success');
                    }else{
                        reject('Failed');
                    }
                }, 3000);
            });
        }

        let onFulfilment = (result) => {
            console.log(result);
        }

        let onRejection = (error) => {
            console.log(error);
        }

        prom(true).then(onFulfilment);
        prom(true).catch(onRejection);

    </script>
</head>
<body></body>
</html>

We can modify above code in more standard and optimized way. We can have used method chain “prom(true).then(onFulfilment).catch(onRejection);” in stead of writing two separate line promise true and false state condition. It will call automatically true status function if it is true else will call false status function.

prom(true).then(onFulfilment);
prom(true).catch(onRejection);

---OR---

prom(true).then(onFulfilment).catch(onRejection);

Also, we can define onFulfilment and onRejection method inside the true, false promise state directly, no need to write separate.

let onFulfilment = (result) => {
    console.log(result);
}

let onRejection = (error) => {
    console.log(error);
}

prom(true).then(onFulfilment);
prom(true).catch(onRejection);

---OR---

prom(true).then((result) => {
    console.log(result);
}).catch((error) => {
    console.log(error);
});

Let us see the our final code : It has less line of code now.

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Advance JavaScript - Promise</title>

    <script>
        function prom(complete){
            return new Promise(function(resolve, reject){
                console.log("Fetching Date, Please Wait...");

                setTimeout(() => {
                    if(complete){
                        resolve('Success');
                    }else{
                        reject('Failed');
                    }
                }, 1000);
            });
        }

        prom(true).then((result) => {
            console.log(result);
        }).catch((error) => {
            console.log(error);
        });

    </script>
</head>
<body></body>
</html>

A promise program which calculate the division of two numbers.

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Advance JavaScript - Promise</title>

    <script>
        function prom(a,b)
        {
            return new Promise(function(resolve, reject){

                console.log('Fetching Calulation. Please wait...');
                
                c = a / b;

                setTimeout(() => {
                    if(a,b){
                        resolve(`Your answer is: ${c}`);
                    }else{
                        reject(`Failed to calculate.`);
                    }
                },2000);

            });
        }

        prom(5,2).then((result) => {
            console.log(result);
        }).catch((error) => {
            console.log(error);
        });


    </script>
</head>
<body></body>
</html>

A promise program using ajax request response.

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Advance JavaScript - Promise</title>

    <script src="https://code.jquery.com/jquery-3.6.0.min.js" crossorigin="anonymous"></script>

    <script>
        function prom()
        {
            return new Promise(function(resolve, reject){
                console.log('Fetching JSON Data. Please wait...');
                setTimeout(()=>{
                    $.get('https://jsonplaceholder.typicode.com/posts', function(data) {
                        resolve(data);
                    }).fail(err => {
                        reject('Failed to load JSON data.');
                    });
                }, 2000);

            });
        }

        prom(true).then((result) => {
            console.log(result);
        }).catch((err) => {
            console.log(err);
        });
    </script>
</head>
<body>

</body>
</html>

Output Window: