A quick note on jQuery.Deferred()

by Bill Forney 6. January 2012 21:53

Just a quick note on jQuery Deferred objects…

   1: var goGetSomeHtml = function() {
   2:     var deferred = $.Deferred();
   3:     $.ajax({
   4:         url: “some.htm”
   5:     }).done(function(data) {
   6:         deferred.resolve(data);
   7:     }).fail(function(jqXHR, textStatus) {
   8:         deferred.reject({ xhr:jqXHR, textStatus: textStatus });
   9:     });
  10:     return deferred.promise();
  11: };

They’re basically a callback wrapper. This example is a bit redundant since jQuery $.ajax returns a Deferred already, but you get the idea. You can use this for anything that requires a callback. It provides a pattern that pushes the callback function into user code in a way that is standardized. The resolve and reject functions on deferred pass their parameters into the callbacks in the done/fail functions.

This lets you pass the deferred promise around (a promise is just a deferred with the resolve/reject removed from its interface). A bit cleaner functional approach that removes the need for you to worry about call/apply syntax and context.

The above can then be used like this:

   1: $.when(
   2:     goGetSomeHtml()
   3: ).done(function(data) {
   4:     //do success callback stuff here...
   5: }).fail(function(state) {
   6:     //use state.xhr or state.textStatus to handle the error somehow.
   7: }

Enjoy. Smile

Digg It!DZone It!StumbleUponTechnoratiRedditDel.icio.usNewsVineFurlBlinkList

Tags: , ,

JavaScript | jQuery

Comments (1) -

1/7/2012 5:29:39 AM #

limitless profits

I really enjoyed reading your post here. Just wanted to say your blog is no slow right here, don't know why exactly. Perhaps you should ask your internet site technician to check it. By the way, keep writing such submit for limitless profits.

limitless profits India

Comments are closed

Powered by BlogEngine.NET 1.6.2.17
Theme by Extensive SEO

Recent Comments

Comment RSS

About the author

William L. Forney was born in Pennsylvania and relocated to Washington State in early 1999. His hobbies include all the usual things: movies, books, music, video games, etc. He writes short sci-fi/fantasy stories which will someday be published in the form of small novels.

Bill's Photograph

He loves computers and has worked in several different areas from web, multimedia, video and 3D animation to database and windows development.

Currently he works at Visible Reality, LLC as the lead developer and improvGroup, LLC as a networking consultant.

He also works with Padgett & Padgett, PLLC, the accounting firm where he setup shop after moving.

His other blog can be found here.