Javascript Promise

The Promise object represents the eventual completion (or failure) of an asynchronous operation and its resulting value.

A Promise is a proxy for a value not necessarily known when the promise is created. It allows you to associate handlers with an asynchronous action’s eventual success value or failure reason. This lets asynchronous methods return values like synchronous methods: instead of immediately returning the final value, the asynchronous method returns a promise to supply the value at some point in the future.

A promise is in one of these states:

  • pending: initial state, neither fulfilled nor rejected.
  • fulfilled: meaning that the operation was completed successfully.
  • rejected: meaning that the operation failed.

A pending promise can either be fulfilled with a value or rejected with a reason (error). When either of these options happens, the associated handlers queued up by a promise’s then method are called. If the promise has already been fulfilled or rejected when a corresponding handler is attached, the handler will be called, so there is no race condition between an asynchronous operation completing and its handlers being attached.

As the then() and catch() methods return promises, they can be chained. The methods promise.then(), promise.catch(), and promise.finally() are used to associate further action with a promise that becomes settled.

<script>
    
let successAction = new Promise((resolve, reject) => {
    console.log('Initial');

    document.getElementById("promisePending").innerHTML = "Starting...";
    // do async action here.

    setTimeout( function() {
        let apiResponse = {};
        apiResponse.id = 1;
        apiResponse.name = "Folau";

        resolve(apiResponse);
        document.getElementById("promiseFullFilled").innerHTML = "fullfilled";

    }, 3000);

});

successAction.then((reponse) => {
    console.log(reponse);
    console.log('Do this');
})
.catch((error) => {
     // This is skiped because resolve is called above.
    console.error('Error');
    console.log(error);
}).finally(() => {
    console.log('finally!');
});

let failedAction = new Promise((resolve, reject) => {
    console.log('Initial');

    document.getElementById("promisePending").innerHTML = "Starting...";
    // do async action here.

    setTimeout( function() {
        let apiResponse = {};
        apiResponse.id = 1;
        apiResponse.name = "Folau";

        reject(apiResponse);
        document.getElementById("promiseRejected").innerHTML = "rejected";

    }, 3000);

});

failedAction.then((reponse) => {
    // This is skiped because reject is called above.
    console.log(reponse);
    console.log('Do this');
})
.catch((error) => {
    console.error('Error');
    console.log(error);
}).finally(() => {
    console.log('finally!');
});

</script>

 

Promise with API HTTP requests

<script>
    const axiosInstance = axios.create({
        baseURL: 'http://localhost:8888',
        timeout: 1000,
        headers: {
            "Content-type": "application/json",
            "token": "foobar"
        }
    });

    function getUser(){
        console.log("getUser");
        let headers = {
            "Content-Type": "application/json",
            "token":"lovemesomecoding-token"
        };

        let options = {};
        options.method = "GET";
        options.headers = headers;

        let id = 1;

        let url = "http://localhost:8888/users/"+id;

        let response = axiosInstance(url, options);

        response.then(response => {
            let data = response.data;
            let content = "";
            content += "id: "+data.id+"<br>";
            content += "firstName: "+data.firstName+"<br>";
            content += "lastName: "+data.lastName+"<br>";
            content += "email: "+data.email+"<br>";

            document.getElementById("getUserContent").innerHTML = content;

        }).catch(error => {
            console.log("error");
            let errorResponse = error.response.data;

            console.log(errorResponse);
            document.getElementById("errorMsg").innerHTML = errorResponse.message;

        });
    }

    function updateUser(){
        console.log("update user");
        let headers = {
            "Content-Type": "application/json",
            "token":"lovemesomecoding"
        };
        let user = {
            firstName: 'Folau',
            lastName: 'Kaveinga',
            email: 'folaukaveinga@gmail.com',
            id: 1
        };

        let options = {};
        options.method = "PUT";
        options.body = JSON.stringify(user);
        options.headers = headers;

        let url = "http://localhost:8888/users";

        let response = axiosInstance(url, options);

        response.then(response => {

            let data = response.data;

            let content = "";
            content += "id: "+data.id+"<br>";
            content += "firstName: "+data.firstName+"<br>";
            content += "lastName: "+data.lastName+"<br>";
            content += "email: "+data.email+"<br>";

            document.getElementById("updateUserContent").innerHTML = content;
            document.getElementById("errorMsg").innerHTML = "";

        }).catch(error => {
            console.log("error");
            let errorResponse = error.response.data;

            console.log(errorResponse);
            document.getElementById("errorMsg").innerHTML = errorResponse.message;

        });
        
    }
    
</script>

Asnyc/await

The async keyword before a function means that function always returns a promise. Other values are wrapped in a resolved promise automatically.

The await keyword makes JavaScript wait until that promise settles and returns its result.

<div class="row">
    <div class="col-1">

    </div>
    <div class="col-4">
        Get Average Number
        <br>
        <button onclick="getAverageNumber()" type="button" class="btn btn-outline-primary">Get It</button>
    </div>
    <div class="col-7" id="averageNum">
        
    </div>
</div>

<script>
    /*
    * Async and await
    */
    async function calculateAverage(num1, num2, num3){

        // This could be a REST API call
        let someNumber = await new Promise(resolve => {
            setTimeout(() => {
                resolve(3);
            }, 2000);
        });
        console.log("num1: "+num1 + ", num2: "+ num2 +", num3: "+ num3 + ", someNumber: "+someNumber);
        return (num1 + num2 + num3 + someNumber) / 4;
    }

    function getAverageNumber(){
        calculateAverage(2, 3, 4).then(average => {
            console.log("average");
            console.log(average);
            document.getElementById("averageNum").innerHTML = average;
        });
    }
</script>

 

Source code on Github




Subscribe To Our Newsletter
You will receive our latest post and tutorial.
Thank you for subscribing!

required
required


Leave a Reply

Your email address will not be published.