Promise
 Pattern
for asynchronous
    JavaScript
 Sebastiaan Deckers — 2012 — BeermatesJS Singapore
What is
  asynchronous
  programming?
Are we there yet? Are we
there yet? Are we there
yet? Are we there yet? ...
When do you use
 asynchronous
 programming?
Performance
 User input, network I/O
 (AJAX), computational
processing, rendering, ...
KISS
       (keep it simple, stupid!)



Separation of concerns,
   Less boilerplate,
Focus on business logic
Asynchronous
  Patterns
  Callbacks,
   Events,
  Promises
Callbacks
$.get('foobar.html', function(data) {
  $('.result').html(data);
  alert('Load was performed.');
});
Problem?
●   Only one callback at a time
●   Nested callbacks: turtles all
          the way down
Events
$('a.button')
  .on('click', function(event) {
    // do something...
  })
  .on('click', function(event) {
    // ... and do something else.
  });
Problem?
●   Hard to synchronise
    multiple events
●   No standard APIs
Promises
                              Asynchronous
                               API Provider



Business Logic     Promise   Asynchronous
                              API Provider



                             Asynchronous
                              API Provider
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...
  });
API Providers
function 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();
    });
  });
}
CommonJS
       Promise/*
http://wiki.commonjs.org/wiki/Promises
The Basics
Business Logic:
 ● when
 ● then


API Provider:
 ● deferred.done
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)

Promise pattern

  • 1.
    Promise Pattern for asynchronous JavaScript Sebastiaan Deckers — 2012 — BeermatesJS Singapore
  • 2.
    What is asynchronous programming? Are we there yet? Are we there yet? Are we there yet? Are we there yet? ...
  • 3.
    When do youuse asynchronous programming?
  • 4.
    Performance User input,network I/O (AJAX), computational processing, rendering, ...
  • 5.
    KISS (keep it simple, stupid!) Separation of concerns, Less boilerplate, Focus on business logic
  • 6.
    Asynchronous Patterns Callbacks, Events, Promises
  • 7.
    Callbacks $.get('foobar.html', function(data) { $('.result').html(data); alert('Load was performed.'); });
  • 8.
    Problem? ● Only one callback at a time ● Nested callbacks: turtles all the way down
  • 9.
    Events $('a.button') .on('click',function(event) { // do something... }) .on('click', function(event) { // ... and do something else. });
  • 10.
    Problem? ● Hard to synchronise multiple events ● No standard APIs
  • 11.
    Promises Asynchronous API Provider Business Logic Promise Asynchronous API Provider Asynchronous API Provider
  • 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.
    API Providers function 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.
    CommonJS Promise/* http://wiki.commonjs.org/wiki/Promises
  • 15.
    The Basics Business Logic: ● when ● then API Provider: ● deferred.done
  • 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)