Sunday 14 August 2016

JQuery Deffered simple example with WebAPI Calls

Jquery Deferred is a new trend in async JS development which made asynchronous programming more flexible, efficient and powerful. I will share my knowledge around JQuery Deferred in this article in a simple way(hopefully) and please do comment with your feedback.

I will also share a sample HTML file which can be used to play around with deferred in your local machine. I strongly suggest a handson in deffered to master the same and the shared sample can also help to an extent.

Deferred object are used to chain multiple callbacks one after another based on success/failure/other state changes. By using this we can make one async call back wait for another and also we can pass data between callback.

There are many methods available with in deferred object and frequently used are as follows
  • promise
  • resolve
  • reject
  • notify
  • done
  • fail
  • progress
  • always
  • then

Simple intro to Deffered method:
  • When a resolved is exectuted in deferred object the method defenition passed into the deferred object's done will be executed
  • When a reject is exectuted in deferred object the method defenition passed into the deferred object's fail method will be executed
  • When a notify is exectuted in deferred object the method defenition passed into the deferred object's progress method will be executed
  • always will be execute on both resolve and reject
  • then will be called after a state change and it can hold method defenition for done,fail and progress as parameters


Promise:

Promise is almost similar to the deferred object, but the promise of a deferred object cannot be used to change the state of deffered. So Promise can only be used to attach events on state change of deferred.

While developing you might see deffered is used intead of promise or viceversa. So if you want the user not to change the state of deferred then expose promise else expose deffered.

Defered supports all above listed functions while promise will support only done, fail, progress, always and then.


Sample Code Snippet:

Note: This HTML file needs you to be in online to work as expected. This is because of CDN and AP calls we have used.

<html>
<head>
    <script src="https://code.jquery.com/jquery-3.1.0.js" integrity="sha256-slogkvB1K3VOkzAI8QITxV3VzpOnkeNVsKvtkYLMjfk=" crossorigin="anonymous"></script>
    <script>
        // Deferred function that returns a deferred promise. If parameter has value then moves to sucess callback else moves to failure callback.
        function deferredFn(Tempv) {
            debugger;
            var Deferredob = $.Deferred();
            Deferredob.notify("Start");
            var request = new XMLHttpRequest();
            request.open("GET", "https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css", true);
            request.send();
            request.onreadystatechange = function () {
                if (this.status == 200) {
                    if (Tempv) {
                        Deferredob.resolve("Resolved")
                    }
                    else {
                        Deferredob.reject("failed")
                    }
                }
            }
            return Deferredob.promise();
        }

        // Method to throw output
        function alertResult(input) {
            alert(input);
        }

        // Main method
        function ram() {
            //deferredFn("Test").then(/*done[success]*/alertResult,/*fail[failure]*/alertResult,/*Progress*/alertResult);

            //deferredFn("Test").progress(alertResult);
            //deferredFn("Test").done(alertResult);
            //deferredFn("Test").fail(alertResult);

            deferredFn().always(alertResult);
        }
    </script>
</head>
<body onload="ram()">
</body>

</html>

PS: Will share some articles whenever I find time.

No comments:

Post a Comment