Click here to Skip to main content
11,573,666 members (54,576 online)
Click here to Skip to main content

Tagged as

jQuery Deferred and Promises

, 4 Mar 2014 CPOL 9.3K 1
Rate this:
Please Sign up or sign in to vote.
As some of you may know I am mainly into WPF/WCF and that sort of stuff, however I like to keep my toe in what is going on within the web world. A while ago (a year I think) I worked with a collegue who was trying to create a TPL like Task construct in […]

As some of you may know I am mainly into WPF/WCF and that sort of stuff,
however I like to keep my toe in what is going on within the web world. A while
ago (a year I think) I worked with a collegue who was trying to create a TPL
like Task construct in Javascript that would support typical TPL things like

  • ContinueWith
  • Wait
  • Result
  • WhenAny

That sort of thing. I also recall he mentioned a JQuery feature called
“Deferred” and “Futures”. I must confess I did not think about this much over
the past year, until I overheard a new work collegue mention “Deferred” and
“Futures”, I thought mmmmm I really need to read up on that. So I did.

There is actually quit a lot out there on this subject, so what I present
here will hardly be cutting edge or novel, but if you have not heard of it before,
it
may at least spike your interest to learn more.

Before I show you a sample lets talk a bit about jQuery Deferred.

In jQuery a Deferred object is an asynchronous activity, which can signal the
success or failure of itself via registered callbacks. Since jQuery 1.5 the
inbuilt jQuery Ajax calls have been using Deferred objects.

You can read more about Deferred here :

http://api.jquery.com/category/deferred-object/
where we can use pipeline
functions such as

  • When
  • Then
  • Done

 

Which is great it means we can compose whole pipelines of these, and only
call a callback when a whole chain is “Done”, or carry on to do some other
thing.

But the true power (at least in my opinion) comes from the fact we can create
$.Deferred objects ourselves.

Here is a trivial example that does a jQuery Get call followed my a timeout
Deferred which I made up, and will only run the callback when both of these is
done.

(function ($) {

    doIt();

    // Jquery Ajax functions are already 
    // Deferred under the hood
    function getData() {
        return $.get('/Dummy.htm');
    }

    // This simple timout method shows how we can easily 
    //create our own deferred functions
    function timeout(x) {
        var dfd = $.Deferred();
        setTimeout(function () {
            dfd.resolve();
        }, x);
        return dfd.promise();
    }

    function doIt() {
        // Don't do anything until both the Ajax call and our 
        // custom Deferred complete
        $.when(getData(), timeout(2000))
        	.done(function (ajaxResult, timeOutResult) {
        	    $('#mainDiv').append(
        	    	'<br/><br/><strong>The animation AND the AJAX request are both done!</strong>');
        	    alert('AJax resultt is \r\n :' + ajaxResult);
        });
    }
})(jQuery);

The key parts you need to pay special attention to are

  • That we create a new Deferred object
  • We resolve the Deferred object when we do the actual work
  • And we return a Promise that we will do the work from the Deferred
    object

This is a very very simple example of using Deferred, but this could be used
for all sorts of novel things, such as :

  • Caching Ajax calls
  • Timeouts (ha ha)
  • Building complex chains of asynchronous functions
  • Commuination with a Web Worker

In fact if you want to see a great TPL/Deferred discussion you can look at
these excellent links:

  1. http://www.scottlogic.co.uk/2011/02/web-workers-part-2-using-jquery-deferred/

  2. http://www.scottlogic.co.uk/2011/02/web-workers-part-3-creating-a-generic-worker/

  3. http://www.scottlogic.co.uk/2011/02/web-workers-part-4-wrapping-it-up/

 

As always here is a small demo project (It is a VS2012 web app, just cos that
easiest for me to create this type of web project) :

https://dl.dropboxusercontent.com/u/2600965/Blogposts/2013/Deferred.zip

 


License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Sacha Barber
Software Developer (Senior)
United Kingdom United Kingdom
I currently hold the following qualifications (amongst others, I also studied Music Technology and Electronics, for my sins)

- MSc (Passed with distinctions), in Information Technology for E-Commerce
- BSc Hons (1st class) in Computer Science & Artificial Intelligence

Both of these at Sussex University UK.

Award(s)

I am lucky enough to have won a few awards for Zany Crazy code articles over the years

  • Microsoft C# MVP 2015
  • Codeproject MVP 2015
  • Microsoft C# MVP 2014
  • Codeproject MVP 2014
  • Microsoft C# MVP 2013
  • Codeproject MVP 2013
  • Microsoft C# MVP 2012
  • Codeproject MVP 2012
  • Microsoft C# MVP 2011
  • Codeproject MVP 2011
  • Microsoft C# MVP 2010
  • Codeproject MVP 2010
  • Microsoft C# MVP 2009
  • Codeproject MVP 2009
  • Microsoft C# MVP 2008
  • Codeproject MVP 2008
  • And numerous codeproject awards which you can see over at my blog

You may also be interested in...

Comments and Discussions

 
-- There are no messages in this forum --
| Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.150624.2 | Last Updated 5 Mar 2014
Article Copyright 2014 by Sacha Barber
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid