SlideShare a Scribd company logo
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)

More Related Content

PPTX
Promises, Promises
PPTX
JavaScript Promises
PDF
JavaScript Promise
PDF
JavaScript Promises
PDF
$q and Promises in AngularJS
PPTX
Avoiding callback hell in Node js using promises
PDF
Callbacks, promises, generators - asynchronous javascript
PDF
Practical JavaScript Promises
Promises, Promises
JavaScript Promises
JavaScript Promise
JavaScript Promises
$q and Promises in AngularJS
Avoiding callback hell in Node js using promises
Callbacks, promises, generators - asynchronous javascript
Practical JavaScript Promises

What's hot (20)

PDF
Javascript Promises/Q Library
PPTX
The Promised Land (in Angular)
PDF
Getting Comfortable with JS Promises
PDF
JavaScript promise
PDF
Asynchronous programming done right - Node.js
PDF
Understanding Asynchronous JavaScript
PPTX
Java Script Promise
PDF
JavaScript Promises
PPTX
Avoiding Callback Hell with Async.js
PDF
Avoiding callback hell with promises
PDF
Boom! Promises/A+ Was Born
PDF
Callbacks and control flow in Node js
PPTX
Async Frontiers
PDF
Web Crawling with NodeJS
PDF
The evolution of asynchronous javascript
PDF
ES6: The Awesome Parts
PPTX
PDF
History of jQuery
PPTX
ES6 is Nigh
PPTX
Good karma: UX Patterns and Unit Testing in Angular with Karma
Javascript Promises/Q Library
The Promised Land (in Angular)
Getting Comfortable with JS Promises
JavaScript promise
Asynchronous programming done right - Node.js
Understanding Asynchronous JavaScript
Java Script Promise
JavaScript Promises
Avoiding Callback Hell with Async.js
Avoiding callback hell with promises
Boom! Promises/A+ Was Born
Callbacks and control flow in Node js
Async Frontiers
Web Crawling with NodeJS
The evolution of asynchronous javascript
ES6: The Awesome Parts
History of jQuery
ES6 is Nigh
Good karma: UX Patterns and Unit Testing in Angular with Karma
Ad

Similar to Promise pattern (20)

PDF
Sane Async Patterns
PDF
Promises are so passé - Tim Perry - Codemotion Milan 2016
PDF
Angular promises and http
PDF
The evolution of asynchronous JavaScript
PPTX
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
PPT
You promise?
PPTX
Async discussion 9_29_15
PDF
Intro to Asynchronous Javascript
PDF
The Asynchronous Pattern (for beginners)
PPTX
asyncjavascript.pptxdgdsgdffgfdgfgfgfdgfdgf
PDF
Event Driven Javascript
PDF
JavaScript Patterns and Principles
PDF
Event driven javascript
PDF
Event driven javascript
PPTX
Promises, promises, and then observables
PDF
Embracing Async with Deferreds and Promises
PDF
How to actually use promises - Jakob Mattsson, FishBrain
PDF
Testing web APIs
PDF
Douglas Crockford: Serversideness
PDF
Asynchronous development in JavaScript
Sane Async Patterns
Promises are so passé - Tim Perry - Codemotion Milan 2016
Angular promises and http
The evolution of asynchronous JavaScript
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
You promise?
Async discussion 9_29_15
Intro to Asynchronous Javascript
The Asynchronous Pattern (for beginners)
asyncjavascript.pptxdgdsgdffgfdgfgfgfdgfdgf
Event Driven Javascript
JavaScript Patterns and Principles
Event driven javascript
Event driven javascript
Promises, promises, and then observables
Embracing Async with Deferreds and Promises
How to actually use promises - Jakob Mattsson, FishBrain
Testing web APIs
Douglas Crockford: Serversideness
Asynchronous development in JavaScript
Ad

Recently uploaded (20)

DOCX
The AUB Centre for AI in Media Proposal.docx
PPT
Teaching material agriculture food technology
PDF
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
PDF
Empathic Computing: Creating Shared Understanding
PDF
NewMind AI Monthly Chronicles - July 2025
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PPTX
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PDF
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
PDF
CIFDAQ's Market Insight: SEC Turns Pro Crypto
PDF
[발표본] 너의 과제는 클라우드에 있어_KTDS_김동현_20250524.pdf
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PDF
KodekX | Application Modernization Development
PDF
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
PPTX
Understanding_Digital_Forensics_Presentation.pptx
PPTX
Cloud computing and distributed systems.
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
PPTX
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
PDF
Review of recent advances in non-invasive hemoglobin estimation
The AUB Centre for AI in Media Proposal.docx
Teaching material agriculture food technology
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
Empathic Computing: Creating Shared Understanding
NewMind AI Monthly Chronicles - July 2025
Diabetes mellitus diagnosis method based random forest with bat algorithm
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication
Per capita expenditure prediction using model stacking based on satellite ima...
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
CIFDAQ's Market Insight: SEC Turns Pro Crypto
[발표본] 너의 과제는 클라우드에 있어_KTDS_김동현_20250524.pdf
“AI and Expert System Decision Support & Business Intelligence Systems”
KodekX | Application Modernization Development
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
Understanding_Digital_Forensics_Presentation.pptx
Cloud computing and distributed systems.
20250228 LYD VKU AI Blended-Learning.pptx
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
Review of recent advances in non-invasive hemoglobin estimation

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 you use 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)