The Promise of jQuery Deferred
Upcoming SlideShare
Loading in...5

The Promise of jQuery Deferred



The Promise JavaScript pattern is receiving quite a lot of attention recently as popular asynchronous pattern. ...

The Promise JavaScript pattern is receiving quite a lot of attention recently as popular asynchronous pattern.

This talk presents the way to understand the concept, how to learn using them step by step and how to design your software based on a real world example.



Total Views
Views on SlideShare
Embed Views



2 Embeds 6 4 2



Upload Details

Uploaded via as Adobe PDF

Usage Rights

CC Attribution-NonCommercial-ShareAlike LicenseCC Attribution-NonCommercial-ShareAlike LicenseCC Attribution-NonCommercial-ShareAlike License

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
Post Comment
Edit your comment

The Promise of jQuery Deferred The Promise of jQuery Deferred Presentation Transcript

  • The Promise ofjQuery Deferred19th April 2013 — jQuery UK
  • Tale Of A UK Job ApplicationAnd Pardon my French1. Submitting an application form2. Being shortlisted3. Phone Interview4. Technical Interview5. Physical Interview6. Salary NegociationThen, accept the contract and relocate or …
  • Lets translate that inJavaScript…
  • (function jobApplication(){(function shortlist(data){(function phoneInterview(){(function technicalInterview(data){(function physicalInterview(){(function salaryNegociation(payload){if (payload.job){acceptContract() && relocate();}else throw SyntaxError("Too bad…");})({ job: "Software Engineer" });})();})({ script: "eval(alert(true);)" });})();})({ why: "I speak JavaScript!" });})();
  • Badge Unlocked: Pyramid ofDoom!
  • Promisification!
  • .var $job = $.Deferred();$jobApplication.progress( updateApplicationState ).done( acceptContract ).done( relocate ).fail( keepCalmAndDrinkWine );$jobApplication.notify({ state: "shortlist" }).notify({ state: "phone_interview" }).notify({ state: "technical_interview" }).notify({ state: "physical_interview" }).notify({ state: "salary_negociation" });$jobApplication.resolve({job: "Software Engineer"});See on JSBin
  • Thomas ParisotFrontend / JavaScript Engineer– –BBC R&D @oncletom
  • Digging into jQuery.DeferredLearning to use Promises, the soft way.
  • Consume the APIIn jQuery 1.8+: $.ajax, $.animate, $(<selector>)var $deferred = $.post(/cheese, {name: "Livarot"});$deferred.done( syncLocalStorage ).done( updateUI ).fail( displayError ).always( logNetworkResponse );
  • Create your first Deferred.function getDelayedUserInput(){var $deferred = $.Deferred();setTimeout(function(){$deferred.resolve(prompt("Anything to say?"));}, 1000);return $deferred;}$(input).on(click, function(e){getDelayedUserInput().done(function(user_input){$(;});});See on JSBin
  • Deal with race conditionworkflowsthen()enables data filtering.when()is a done()for multiple promises.$.when( $.getJSON(/page/1), $.getJSON(/page/2) ).then(function(page1_data, page2_data){return page1_data.concat(page2_data);}).done( displayCombinedData ).fail( displayError );
  • Sharing safely your DeferredjQuery.Deferredvs. Deferred.promise()..var $deferred = $.Deferred();var $promise = $deferred.promise();$promise.done(function(value){console.log("Oh my "+value);});// $promise is read-only$promise.resolve("gosh");// will log Oh my head$deferred.resolve("head");See on JSBin
  • Improving our first Deferred.function getDelayedUserInput(){var $deferred = $.Deferred();setTimeout(function(){$deferred.resolve(prompt("Anything to say?"));}, 1000);return $deferred.promise(); // now safe}$(input).on(click, function(e){getDelayedUserInput().done(function(user_input){$(;});});See on JSBin
  • Tale of a country relocationLets use another real life example (thats still better than Hello world examples).1. opening a bank account2. finding a new place to live3. request a NINo4. ask for a debit cardAnd hope for an on-time payday to finally live like a newsettler!
  • Opening a bank accountfunction requestBankAccount(job, postal_address){var $deferred;// expect an account object to be resolved$deferred = $.post(, {job: job,address: postal_address});return $deferred.promise();}
  • Assembling the workflowLets assume we have a $jobpromise available in the scope.var $address, $account, $NINo, $debitCard;$address = requestAppartment(job);$.when($job, $address).done(function(job, address){$account = requestBankAccount(job, address);$NINo = requestNINo(job, address);$account.done(function(account){$debitCard = requestDebitCard(account, address);});});
  • Killing the FUDThe Internet told me:the Promises are everythingthe Promises are Evil
  • Callback vs. Promise vs.EventCallbacks are for easy and simple uses.Events are for vertical code expansion.nodes.value(function(item){return item.service_id;});MyModule.prototype.init = function init(view){view.$submit.on(click, this.handleSubmit);view.$document.on(click keyup, this.logEvent);};
  • When to use them?Some considerations to think about to know when to usePromises.simplifying a workflow contractflattening code nestingundeterminate duration async taskcoordinating multiple async taskstl;dr: modularize chained tasks.
  • jQuery Deferred is notPromise/A+ compliantWho cares? As long as it helps you to:simplify your codekeep your code maintainable (for you and your peers)
  • Remember kidsPatterns and tools help to solve problems.You solve the problems.FUD solves nothing.
  • To infinity and beyond!Libraries: , ,jQuery Deferred APICommonJS Promise/A+ECMAScript PromisesDOM Futureasync ff q
  • Thanks everybodyHave a question? Come talk / tweet / email to me.