Promises & Deferredslook into the async future@slicejs
Plan1. Introduction2. What problem promises can solve ?3. Promises in jQuery
Promises are aprogramming constructthat have been aroundsince 1976.http://en.wikipedia.org/wiki/Futures_and_promises
Brief History of Promises● Term was first used by C++ engineers on the Xanadu project (1976)● 2007: Dojo Framework added d...
What is a Promise ?A Promise is an object that represents a task with twopossible outcomes (success or failure)holds callb...
Promises & DeferredsPromise represents a value that is not yetknownDeferred represents work that is not yetfinished
CommonJS Promises/A specProposal by Kris Zyp
Whats inside ?The Promises /A Proposal suggests the following standard behavior and APIregardless of implementation detail...
then(fulfilledHandler,errorHandler,progressHandler);
Whats insideA promise:● has a function as a value for the property then(which must return a promise )● Adds a fulfilledHan...
Current implementations● Kris Kowal’s Q.js● AJ ONeal’s FuturesJS● jQuery since 1.5Q.js - implementation of the Promises/A ...
Why do we needpromises ?
sync !== async
But they exist parallely
How do we manage this ?
Anybody ?
We used to use callbacksA callback is a piece of executable code that is passed asan argument to other code, which is expe...
Theres nothing wrongwith themuntil...
Do you know that ?step1(function (value1) {step2(value1, function(value2) {step3(value2, function(value3) {step4(value3, f...
Such a case - "Taka sytuacja"● make an Ajax request to get some data● do something with data, then● do other things
Insights● request is made● execution of our program isnt stopped while the server is responding● By the time we get the re...
Wouldnt be betterdoStuff();that way ?
var $doStuff = $.Deferred();$doStuff.done(doOtherStuff).fail(keepCalmAndDrinkWine);doStuff() - easier way
Lets take a closerlook on Deferredobjectthen
DeferredPromise(A)Handlers States$.then() $.when()hashas hasbased onrepresented byas unfinished workas yet unknown valuewh...
Promise - states & flowsPromiseunfulfilled fulfilledfailed
Promises can help
We can writeasynchronous JavaScriptparallel to how we writesynchronous code
Where to use promises● Ajax● Timing tasks (games)● Synchronizing parallel tasks with $.when()● Decoupling events and appli...
We love jQuery (dont we ?)Lets take a look at theirimplementation
jQuery 1.5 changed Mr. Ajaxsince(version1.5) {$.ajax();$.get();$.post();return Promises;} thats amazing !
Deferreds team in complete$.Deferred();deferred.always();deferred.then();deferred.when();deferred.resolve(); or deferred.r...
How to use them ?
Instantiate Deferredvar future = $.Deferred();
$.Deferred()A constructor that creates a new deferred object.Accepts an optional init function which will be executedimmed...
Place your toys & voilavar step1, step2, url;url = example.json;step1 = $.ajax(url);step2 = step1.then(function (data) {se...
deferred.then();Adds handlers which will be called on● resolved● rejected or in● progressandreturns a promise;
deferred.when();Returns a new promise based on the completion ofmultiple promises.If any promise is rejected,.when() is re...
deferred.when();function taskOne() {setTimeout(function() {console.log(task1);}, 1000);}function taskTwo() {setTimeout(fun...
Examplevar prompt = $.Deferred();$(#playGame).focus().on(keypress, function(e) {var Y = 121, N = 110;if(e.keyCode === Y) {...
Few things to remember● callbacks in order in which they were bound● Promise can be resolved or rejected only once
jQuery vs. CommonJs Promises/A● implementation are nearly identical● they use the same words to mean different things● jQu...
Thank you
Code showcase
Discussionthen
Images used in presentation● Callback memhttp://i.imgur.com/dHCqj.jpg● Thank you image http://media.tumblr.com/cda999f9eb5...
Links from presentation● CommonJS Promises / A spechttp://wiki.commonjs.org/wiki/Promises/Ahttp://wiki.commonjs.org/wiki/P...
Promises look into the async future
Upcoming SlideShare
Loading in …5
×

Promises look into the async future

853 views
656 views

Published on

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

No Downloads
Views
Total views
853
On SlideShare
0
From Embeds
0
Number of Embeds
1
Actions
Shares
0
Downloads
0
Comments
0
Likes
2
Embeds 0
No embeds

No notes for slide

Promises look into the async future

  1. 1. Promises & Deferredslook into the async future@slicejs
  2. 2. Plan1. Introduction2. What problem promises can solve ?3. Promises in jQuery
  3. 3. Promises are aprogramming constructthat have been aroundsince 1976.http://en.wikipedia.org/wiki/Futures_and_promises
  4. 4. Brief History of Promises● Term was first used by C++ engineers on the Xanadu project (1976)● 2007: Dojo Framework added dojo.Deferred● 2009: dojo.Deferred influenced Kris Zyp - Proposal of CommonJSPromises/A spec.● 2009: Node.js - used Promises in its non blocking API● 2009: two implementations (Kris Kowal Q.js and ONeill Futures.js)● 2011: jQuery rewrites Ajax - ( not 100% CommonJS spec compliant )20071976 2009 2011
  5. 5. What is a Promise ?A Promise is an object that represents a task with twopossible outcomes (success or failure)holds callbacks that fire when one outcome or theother has occurred
  6. 6. Promises & DeferredsPromise represents a value that is not yetknownDeferred represents work that is not yetfinished
  7. 7. CommonJS Promises/A specProposal by Kris Zyp
  8. 8. Whats inside ?The Promises /A Proposal suggests the following standard behavior and APIregardless of implementation details.A promise has 3 possible states: unfulfilled, fulfilled and failed.● unfulfilled: since a promise is a proxy for an unknown value it starts inan unfulfilled state● fulfilled: the promise is filled with the value it was waiting for● failed: if the promise was returned an exception, it is in the failed state.
  9. 9. then(fulfilledHandler,errorHandler,progressHandler);
  10. 10. Whats insideA promise:● has a function as a value for the property then(which must return a promise )● Adds a fulfilledHandler, errorHandler, and progressHandler to be calledfor completion of a promise.● then(fulfilledHandler, errorHandler, progressHandler);
  11. 11. Current implementations● Kris Kowal’s Q.js● AJ ONeal’s FuturesJS● jQuery since 1.5Q.js - implementation of the Promises/A specFutures - is a broader toolkit, incorporating many of the flow controlfeatures found in libraries like Async.js.jQuery - not 100% Promises/A compliant.https://github.com/kriskowal/qhttps://github.com/coolaj86/futures
  12. 12. Why do we needpromises ?
  13. 13. sync !== async
  14. 14. But they exist parallely
  15. 15. How do we manage this ?
  16. 16. Anybody ?
  17. 17. We used to use callbacksA callback is a piece of executable code that is passed asan argument to other code, which is expected to call back(execute ) the argument at some convenient time— Wikipedia
  18. 18. Theres nothing wrongwith themuntil...
  19. 19. Do you know that ?step1(function (value1) {step2(value1, function(value2) {step3(value2, function(value3) {step4(value3, function(value4) {// Do something with value4});});});});
  20. 20. Such a case - "Taka sytuacja"● make an Ajax request to get some data● do something with data, then● do other things
  21. 21. Insights● request is made● execution of our program isnt stopped while the server is responding● By the time we get the response data from our Ajax request, theprogram has already finished execution
  22. 22. Wouldnt be betterdoStuff();that way ?
  23. 23. var $doStuff = $.Deferred();$doStuff.done(doOtherStuff).fail(keepCalmAndDrinkWine);doStuff() - easier way
  24. 24. Lets take a closerlook on Deferredobjectthen
  25. 25. DeferredPromise(A)Handlers States$.then() $.when()hashas hasbased onrepresented byas unfinished workas yet unknown valuewhat to do once work is donead value is knownpending = unfulfilled = waitingfulfilled = resolved = successrejected = failed = errorhold off doing things until youhave result of doing thatDeferred objectexecute callbacks based on oneor more objects that representsasync events
  26. 26. Promise - states & flowsPromiseunfulfilled fulfilledfailed
  27. 27. Promises can help
  28. 28. We can writeasynchronous JavaScriptparallel to how we writesynchronous code
  29. 29. Where to use promises● Ajax● Timing tasks (games)● Synchronizing parallel tasks with $.when()● Decoupling events and application logic● Animations
  30. 30. We love jQuery (dont we ?)Lets take a look at theirimplementation
  31. 31. jQuery 1.5 changed Mr. Ajaxsince(version1.5) {$.ajax();$.get();$.post();return Promises;} thats amazing !
  32. 32. Deferreds team in complete$.Deferred();deferred.always();deferred.then();deferred.when();deferred.resolve(); or deferred.reject();deferred.promise();deferred.state();deferred.done();deferred.fail();$.ajax();
  33. 33. How to use them ?
  34. 34. Instantiate Deferredvar future = $.Deferred();
  35. 35. $.Deferred()A constructor that creates a new deferred object.Accepts an optional init function which will be executedimmediately after the deferred is created.
  36. 36. Place your toys & voilavar step1, step2, url;url = example.json;step1 = $.ajax(url);step2 = step1.then(function (data) {setTimeout(function () {console.log(Request completed);}, 3000);});step2.done(function () {console.log(Sequence completed)});});
  37. 37. deferred.then();Adds handlers which will be called on● resolved● rejected or in● progressandreturns a promise;
  38. 38. deferred.when();Returns a new promise based on the completion ofmultiple promises.If any promise is rejected,.when() is rejected and if all promises are resolved, it isresolved.
  39. 39. deferred.when();function taskOne() {setTimeout(function() {console.log(task1);}, 1000);}function taskTwo() {setTimeout(function() {console.log(task1);}, 3000);}$.when(taskOne, taskTwo).done(function () {console.log(taskOne and taskTwo are finished);});
  40. 40. Examplevar prompt = $.Deferred();$(#playGame).focus().on(keypress, function(e) {var Y = 121, N = 110;if(e.keyCode === Y) {prompt.resolve();} else if (e.keyCode === N) {prompt.reject();} else {return false;}});prompt.always(function(){console.log(A choice was made:);});prompt.done(function(){ console.log(Starting game...); });prompt.fail(function(){ console.log(No game today.); });
  41. 41. Few things to remember● callbacks in order in which they were bound● Promise can be resolved or rejected only once
  42. 42. jQuery vs. CommonJs Promises/A● implementation are nearly identical● they use the same words to mean different things● jQuery uses resolve as opposite of fail● Promises/A uses fullfill● jQ 1.8 then method (shorthand done, fail and progress)● jQ then === pipe (pipe from 1.8+ deprecated)● noticeable in the case of error handling
  43. 43. Thank you
  44. 44. Code showcase
  45. 45. Discussionthen
  46. 46. Images used in presentation● Callback memhttp://i.imgur.com/dHCqj.jpg● Thank you image http://media.tumblr.com/cda999f9eb5857ea62323368f1a94577/tumblr_inline_misrk5wRf81qz4rgp.gif● jQuery logohttp://upload.wikimedia.org/wikipedia/en/9/9e/JQuery_logo.svg● Dojo logohttp://www.socialseomanagement.com/sites/default/files/dojo.png● Ajax can http://www.walgreens.com/dbimagecache/03500005360_450x450_a.jpg?01AD=3L88KEUeA9XexrvKpx8FNgPIx6lu4gfXFVidRMbWTJqGPihxbA-UDiQ&01RI=71DA49E5EE1856F&01NA=
  47. 47. Links from presentation● CommonJS Promises / A spechttp://wiki.commonjs.org/wiki/Promises/Ahttp://wiki.commonjs.org/wiki/Promises/A● Ksis Zyp Githubhttps://github.com/kriszyp● Q.js library (github)https://github.com/kriskowal/q● Futures js (github)https://github.com/coolaj86/futures● jQuery Deferred APIhttp://api.jquery.com/category/deferred-object/● Promises libraries perf testhttps://github.com/cujojs/promise-perf-tests

×