Promise pattern

9,396 views

Published on

Published in: Technology, Design

Promise pattern

  1. 1. Promise Patternfor asynchronous JavaScript Sebastiaan Deckers — 2012 — BeermatesJS Singapore
  2. 2. What is asynchronous programming?Are we there yet? Are wethere yet? Are we thereyet? Are we there yet? ...
  3. 3. When do you use asynchronous programming?
  4. 4. Performance User input, network I/O (AJAX), computationalprocessing, rendering, ...
  5. 5. KISS (keep it simple, stupid!)Separation of concerns, Less boilerplate,Focus on business logic
  6. 6. Asynchronous Patterns Callbacks, Events, Promises
  7. 7. Callbacks$.get(foobar.html, function(data) { $(.result).html(data); alert(Load was performed.);});
  8. 8. Problem?● Only one callback at a time● Nested callbacks: turtles all the way down
  9. 9. Events$(a.button) .on(click, function(event) { // do something... }) .on(click, function(event) { // ... and do something else. });
  10. 10. Problem?● Hard to synchronise multiple events● No standard APIs
  11. 11. Promises Asynchronous API ProviderBusiness Logic Promise Asynchronous API Provider Asynchronous API Provider
  12. 12. Business Logic(new Promise) .when(load_asset(maps/lobby.bsp)) .when(load_asset(music/intro.ogg)) .when(choose_name()) .then(function() { // everything loaded, start the game... });
  13. 13. API Providersfunction load_asset(path) { return new Promise(function(deferred) { $.get(path, deferred.done); });}function choose_name() { var valid = /^[a-zA-Z0-9_]+$/; return new Promise(function(deferred) { $(form).submit(function() { if(valid.test($(.name).val())) deferred.done(); }); });}
  14. 14. CommonJS Promise/*http://wiki.commonjs.org/wiki/Promises
  15. 15. The BasicsBusiness Logic: ● when ● thenAPI Provider: ● deferred.done
  16. 16. The Tricks.when().when() // parallel chaining.then().then() // multiple listeners.asap() // Race condition// Edge cases.deferred.failure(reason).then(success, error)// Progress tracking.deferred.progress(amount).then(success, error, progress)

×