Deferred Object In jQuery

Deferred object is very easy to understand. I will try to give its explanation in a very short and up to point manner.

While reading this post, please use this example and try it yourself to get more idea.

Generally Deferred means something to be postponed. In the same way deferred objects start executing when state of deferred object is resolved or rejected, until then it is like postponed and waiting to execute.

If you look below code, we simply try to create a deferred object and resolved it.

Read comment carefully,

var defObj = function() {
    var dfd = $.Deferred();
    --Created deferred object
    dfd.resolve();
    --need to resolve / reject it otherwise it remains unresolved
    return dfd;
    --returning deferred object
}
defObj().done(function() 
    --see if deferred object is resolved or rejected only then here sucess
    --or fail method execute {
        alert("success");
    }).fail(function() {
    alert("fail");
});

In above example if you comment dfd.resolve() method then no alert message is displayed. Remember only resolved or rejected deferred object gets executed. 

If you use resolve() method on deferred object it calls success method so in that case alert displays a success message.

If you use reject() method on deferred object it calls fail method so in that case alert displays fail message.

Now instead of dfd.resolve(); use dfd.reject(); and check. You will get fail message in alert.

So far deferred object is clear.

Now when we invoke deferred object like defObj().done() at that time any one can temper with it, calling defObj.reject().

So how to make it safe and not allow to exploit it by others? the answer is use promise() mehod. So outside of that function scope it is not allowed to change state of deferred object.

So instead of returning deferred object like return dfd; use return dfd.promise();

Now check following example,

var defObj = function() {
    var dfd = $.Deferred();
    const myTimeout = setTimeout(function() {
        dfd.reject("argument value");
    }, 5000);
    return dfd.promise();
}
defObj().then(function(data) {
    alert("sucess called " + data);
}, function(data) {
    alert("reject called " + data);
});

In the above example, we use setTimeout method to delay changing deferred object status to rejected, so after 5 second alert is displayed.

Till that time deferred object does not get executed, this is real use of deferred object.

In real scenario, you want to do some ajax call and then on that success or fail you want to invoke some method passing some arguments.

To pass arguments you can pass while calling resolve(args) or reject(args).

So these arguments are passed to success or fail function. In the above case we pass like dfd.reject("argument value"), and this is rejected call so it created alert message like "reject called argument value".

Please like and comment if you are really happy with sharing.