JavaScript Promise Use Cases

Yeah yeah another JS fatigue and stuff to learn from the net again. Well today, is just a refreshed tutorial of my previous archive post namely use cases of Javascript Promise .

promise is an object that may produce a single value some time in the future : either a resolved value, or a reason that it’s not resolved (e.g., a network error occurred). yada yada theory part over. By 2014 almost all major browser support it except IE 11 and some opera variants. Every since then, its has been a javascript cooking ingredient.

Let’s move on to some practical part of it.

I’ll be writing a simple html template to prep the demo up, also will be needing some simple jquery for ajax. So, we are just gonna borrow it from the CDN.

<html>
    <head>
        <title>Always Promise</title>
        <script crossorigin="anonymous" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
        <link href="https://fonts.googleapis.com/css?family=Slabo+27px&display=swap" rel="stylesheet">
        <style>
            * {
                font-family: 'Slabo 27px', serif;
            }
        </style>
    </head>
    <body>
        <h1>Ajax Data Results</h1>
        <ul id="resultPlace"></ul>
        <script></script>
</body>
</html>

Next up, let’s write a simple Promise function which, goes like this.

let promise = new Promise(function(resolve, reject) {
  // executor function here.
  // you can use resolve(), and reject() here. 
});

We are going to write a Promise function called to call some WebAPI namely, callEssentialAjax. We are going to create a scenario that, you need to have two results in two different API calls to do some stuff and any failure in returning either one of the results will just fail the whole process and maybe we are going to prompt the user to try again etc.

<html>
    <head>
        <title>Always Promise</title>
        <script crossorigin="anonymous" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
        <link href="https://fonts.googleapis.com/css?family=Slabo+27px&display=swap" rel="stylesheet">
        <style>
            * {
                font-family: 'Slabo 27px', serif;
            }
        </style>
    </head>
    <body>
        <h1>Ajax Data Results</h1>
        <ul id="resultPlace"></ul>
        <script>
            //Some google API that returns some country code and phone codes.
            var url1 = "https://script.google.com/macros/s/AKfycbyWx63L82e2DqT50ILpYL6rpGXakBaRteP-gzqdg-tnI1-xTEs/exec";
            var url2 = "https://script.google.com/macros/s/AKfycbz6dsPaXOboi_ops9RaGAT1msjak4QTob1Blv8XR5ySxSrEmgVm/exec";

            function callEssentialAjax(urlParam) {
                var ajaxPromise = new Promise(function (resolve, reject) { 
                    //Below this line is the executor in my case, is the ajax.
                    var request = $.ajax({url: urlParam});
                    request.done(function (values) { 
                        //This ajax call is successful. Pass!
                        result = values;
                        result.origin = urlParam;
                        result.status = "OK";
                        resolve(result);
                    });
                    request.fail(function (reason) { 
                        //This ajax call failed. Reject Promise.
                        result = reason;
                        result.origin = urlParam;
                        result.status = "Failed";
                        reject(result);
                    });
                });

                return ajaxPromise;
            }
        </script>
</body>
</html>

Then, we can cook some more of our Promise by chaining them with Promise.all function which makes a batch promise.

<html>
    <head>
        <title>Always Promise</title>
        <script crossorigin="anonymous" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
        <link href="https://fonts.googleapis.com/css?family=Slabo+27px&display=swap" rel="stylesheet">
        <style>
            * {
                font-family: 'Slabo 27px', serif;
            }
        </style>
    </head>
    <body>
        <h1>Ajax Data Results</h1>
        <ul id="resultPlace"></ul>
        <script>
            var url1 = "https://script.google.com/macros/s/AKfycbyWx63L82e2DqT50ILpYL6rpGXakBaRteP-gzqdg-tnI1-xTEs/exec";
            var url2 = "https://script.google.com/macros/s/AKfycbz6dsPaXOboi_ops9RaGAT1msjak4QTob1Blv8XR5ySxSrEmgVm/exec";

            function callEssentialAjax(urlParam) {
                var ajaxPromise = new Promise(function (resolve, reject) { // Below this line is the executor in my case, is the ajax.
                    var request = $.ajax({url: urlParam});
                    request.done(function (values) { // This ajax call is successful. Pass!
                        result = values;
                        result.origin = urlParam;
                        result.status = "OK";
                        resolve(result);
                    });
                    request.fail(function (reason) { // This ajax call failed. Reject Promise.
                        result = reason;
                        result.origin = urlParam;
                        result.status = "Failed";
                        reject(result);
                    });
                });

                return ajaxPromise;
            }


            var promisesArray = [];
            promisesArray.push(callEssentialAjax(url1));
            promisesArray.push(callEssentialAjax(url2));
            // Promise.all accepts all promise objects in an array.
            $("#resultPlace").html("");
            var promiseHandler = Promise.all(promisesArray);
            promiseHandler.then(function (values) {
                console.log("All the promises are resolved", values);
                for (var i = 0; i < values.length; i++) {
                    //Loop array of results because, there is two promises.
                    $("#resultPlace").append("<li>URL " + values[i].origin + " : " + values[i].status + "</li> ");
                }
            });
            promiseHandler.catch(function (reason) {
                console.log("One of the promises failed with the following reason", reason);
                $("#resultPlace").append("<li>URL " + reason.origin + " : " + reason.status + "</li> ");
            });
        </script>
    </body>
</html>

Result in running this code, will give you something like the picture below.

Now let’s tweak the code. Let’s see what happens if we fail url2. Simply just append some character behind the URL to force a fail. I’m gonna just append LOL
e.g.

var url2 = "https://script.google.com/macros/s/AKfycbz6dsPaXOboi_ops9RaGAT1msjak4QTob1Blv8XR5ySxSrEmgVm/execLOL";

Retest the page, you will see an error. Now that you see there’s a use case for this. Step back and rethink a little on how you can apply this further. Perhaps now we can place our progress loader/spinner in a more centralized area rather than within every ajax call you are making just to name a few. You will know that Promise actually makes controlling of API calls much easier.

I hope this helps and best of luck! :).

Comments

comments