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. ...
Lets translate that inJavaScript…
(function jobApplication(){(function shortlist(data){(function phoneInterview(){(function technicalInterview(data){(functi...
Badge Unlocked: Pyramid ofDoom!
Promisification!
.var $job = $.Deferred();$jobApplication.progress( updateApplicationState ).done( acceptContract ).done( relocate ).fail( ...
Thomas ParisotFrontend / JavaScript Engineer– –BBC R&D IRFSoncle-tom.net @oncletom github.com/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"});$deferre...
Create your first Deferred.function getDelayedUserInput(){var $deferred = $.Deferred();setTimeout(function(){$deferred.res...
Deal with race conditionworkflowsthen()enables data filtering.when()is a done()for multiple promises.$.when( $.getJSON(/pa...
Sharing safely your DeferredjQuery.Deferredvs. Deferred.promise()..var $deferred = $.Deferred();var $promise = $deferred.p...
Improving our first Deferred.function getDelayedUserInput(){var $deferred = $.Deferred();setTimeout(function(){$deferred.r...
Tale of a country relocationLets use another real life example (thats still better than Hello world examples).1. opening a...
Opening a bank accountfunction requestBankAccount(job, postal_address){var $deferred;// expect an account object to be res...
Assembling the workflowLets assume we have a $jobpromise available in the scope.var $address, $account, $NINo, $debitCard;...
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(fun...
When to use them?Some considerations to think about to know when to usePromises.simplifying a workflow contractflattening ...
jQuery Deferred is notPromise/A+ compliantWho cares? As long as it helps you to:simplify your codekeep your code maintaina...
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.
Upcoming SlideShare
Loading in …5
×

The Promise of jQuery Deferred

3,831 views
3,688 views

Published on

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.

Published in: Technology
0 Comments
5 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
3,831
On SlideShare
0
From Embeds
0
Number of Embeds
15
Actions
Shares
0
Downloads
31
Comments
0
Likes
5
Embeds 0
No embeds

No notes for slide

The Promise of jQuery Deferred

  1. 1. The Promise ofjQuery Deferred19th April 2013 — jQuery UK
  2. 2. 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 …
  3. 3. Lets translate that inJavaScript…
  4. 4. (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!" });})();
  5. 5. Badge Unlocked: Pyramid ofDoom!
  6. 6. Promisification!
  7. 7. .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
  8. 8. Thomas ParisotFrontend / JavaScript Engineer– –BBC R&D IRFSoncle-tom.net @oncletom github.com/oncletom
  9. 9. Digging into jQuery.DeferredLearning to use Promises, the soft way.
  10. 10. Consume the APIIn jQuery 1.8+: $.ajax, $.animate, $(<selector>)var $deferred = $.post(/cheese, {name: "Livarot"});$deferred.done( syncLocalStorage ).done( updateUI ).fail( displayError ).always( logNetworkResponse );
  11. 11. 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){$(e.target).val(user_input);});});See on JSBin
  12. 12. 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 );
  13. 13. 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
  14. 14. 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){$(e.target).val(user_input);});});See on JSBin
  15. 15. 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!
  16. 16. Opening a bank accountfunction requestBankAccount(job, postal_address){var $deferred;// expect an account object to be resolved$deferred = $.post(http://bank.com/account, {job: job,address: postal_address});return $deferred.promise();}
  17. 17. 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);});});
  18. 18. Killing the FUDThe Internet told me:the Promises are everythingthe Promises are Evil
  19. 19. 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);};
  20. 20. 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.
  21. 21. 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)
  22. 22. Remember kidsPatterns and tools help to solve problems.You solve the problems.FUD solves nothing.
  23. 23. To infinity and beyond!Libraries: , ,jQuery Deferred APICommonJS Promise/A+ECMAScript PromisesDOM Futureasync ff q
  24. 24. Thanks everybodyHave a question? Come talk / tweet / email to me.

×