Saturday, September 27, 2014

Understanding Deferred in JQuery

Simplest example of ajax request in JQuery.

        $.ajax('http://ip.jsontest.com/', {
            success: function (result) {
                console.log('success');
            },
            error: function (err) {
                console.log('error');
            }
        });

Result of success callback function will have 3 parameters, which are "Anything (any type of) data, String textStatus, jqXHR jqXHR".


You can check the state of jqXHR object using jqXHR().state(), If you check with beforeSend event, you can see the state is pending before request is sent. Sometimes you'll get “No 'Access-Control-Allow-Origin' header is present on the requested resource” error.

$.ajax also returns jqXHR object. You can assign multiple callbacks to this.

        var a = $.ajax({
            url: 'http://jsonplaceholder.typicode.com/posts/1',
            success: function (data) {
                console.log(data);
            },
            error: function (data) {
                console.log(data);
            }
        });

        a.done(function (result) {
            console.log('done : ' + result);
        });

        a.then(function (result) {
            console.log('then : ' + result);
        });

        a.error(function (result) {
            console.log('error : ' + result);
        });

here after sending the ajax request, the object immediately returns and other callbacks are attached. Still the ajax state is pending, If success callback get hits, state becomes resolved and then callbacks are called.

If it hits error state is rejected. done or then callbacks won'get called but error callback will get called. then() can also have failCallback attached like below,

        a.then(function (result) {
            console.log('then : ' + result);
        }, errorCallback);

        function errorCallback(err) {
            console.log(err);
        }

If you specify this, errorCallback will get called if an error occurs.

jQuery.when()
accepts one or more objects and provide a way to execute callback functions. Usually deferred. If single Deferred is passed, its Promise is returned.

            function ajaxCall() {
                return $.ajax({
                    url: 'http://jsonplaceholder.typicode.com/posts/1',
                })
                .done(function (data) {
                    console.log(data);
                })
                .fail(function (data) {
                    console.log(data);
                })
            }

            function function2() {
                debugger;
            }

            var a = $.when(ajaxCall());
            a.then(function2);

If a single argument is passed to $.when which is not a Deferred or a promise, It'll be treated as resolved and attached callbacks will be called. Above if you don't return anything from ajaxCall(), a will be resolved and function2 will be executed without waiting for ajaxCall to be finished. Since your Deferred never gets rejected, fail callbacks are never get called. If Deferred resolved with no value, callbacks will get undefined value.

If you return ajax, a will be at pending state until ajaxCall() is finished and then only function2 gets executed.

deferred.then()
Add handlers to be called when deferred object is resolved, rejected or pending.

If we expand on the example above, here you can attach fallCallbacks as well.

            function failPath() {
                debugger;
            }

            var a = $.when(ajaxCall());
            a.then(happyPath, failPath);

deferred.done()
Handlers to be called when deferred object is resolved

        var defer = $.Deferred();
        defer.done(function (val) {
            console.log(val);
        });

        defer.then(function (val) {
            console.log(val);
        }, function (val) {
            console.log(val);
        });

if defer.resolve()
done callback and then's done callback will be called

if defer.reject()
done callback won't get called. then's fail callback will get called.

You can check active Ajax requests using $.active function. See this


0 comments:

Post a Comment

Powered by Blogger.


Software Architect at Surge Global/ Certified Scrum Master

Experienced in Product Design, Software Engineering, Team management and Practicing Agile methodologies.

Search This Blog

Facebook