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

What's hot (20)

PDF
Javascript Promises/Q Library
async_io
 
PPTX
The Promised Land (in Angular)
Domenic Denicola
 
PDF
Getting Comfortable with JS Promises
Asa Kusuma
 
PDF
JavaScript promise
eslam_me
 
PDF
Asynchronous programming done right - Node.js
Piotr Pelczar
 
PDF
Understanding Asynchronous JavaScript
jnewmanux
 
PPTX
Java Script Promise
Alok Guha
 
PDF
JavaScript Promises
Derek Willian Stavis
 
PPTX
Avoiding Callback Hell with Async.js
cacois
 
PDF
Avoiding callback hell with promises
TorontoNodeJS
 
PDF
Boom! Promises/A+ Was Born
Domenic Denicola
 
PDF
Callbacks and control flow in Node js
Thomas Roch
 
PPTX
Async Frontiers
Domenic Denicola
 
PDF
Web Crawling with NodeJS
Sylvain Zimmer
 
PDF
The evolution of asynchronous javascript
Alessandro Cinelli (cirpo)
 
PDF
ES6: The Awesome Parts
Domenic Denicola
 
PPTX
Domains!
Domenic Denicola
 
PDF
History of jQuery
jeresig
 
PPTX
ES6 is Nigh
Domenic Denicola
 
PPTX
Good karma: UX Patterns and Unit Testing in Angular with Karma
ExoLeaders.com
 
Javascript Promises/Q Library
async_io
 
The Promised Land (in Angular)
Domenic Denicola
 
Getting Comfortable with JS Promises
Asa Kusuma
 
JavaScript promise
eslam_me
 
Asynchronous programming done right - Node.js
Piotr Pelczar
 
Understanding Asynchronous JavaScript
jnewmanux
 
Java Script Promise
Alok Guha
 
JavaScript Promises
Derek Willian Stavis
 
Avoiding Callback Hell with Async.js
cacois
 
Avoiding callback hell with promises
TorontoNodeJS
 
Boom! Promises/A+ Was Born
Domenic Denicola
 
Callbacks and control flow in Node js
Thomas Roch
 
Async Frontiers
Domenic Denicola
 
Web Crawling with NodeJS
Sylvain Zimmer
 
The evolution of asynchronous javascript
Alessandro Cinelli (cirpo)
 
ES6: The Awesome Parts
Domenic Denicola
 
History of jQuery
jeresig
 
ES6 is Nigh
Domenic Denicola
 
Good karma: UX Patterns and Unit Testing in Angular with Karma
ExoLeaders.com
 

Similar to Promise pattern (20)

PDF
Asynchronous development in JavaScript
Amitai Barnea
 
PDF
Intro to Asynchronous Javascript
Garrett Welson
 
PDF
Async js - Nemetschek Presentaion @ HackBulgaria
HackBulgaria
 
PDF
The evolution of java script asynchronous calls
Huy Hoàng Phạm
 
PDF
Async JavaScript Unit Testing
Mihail Gaberov
 
KEY
Node.js
Mat Schaffer
 
PDF
Fundamental Node.js (Workshop bersama Front-end Developer GITS Indonesia, War...
GITS Indonesia
 
PPTX
I Know It Was MEAN, But I Cut the Cord to LAMP Anyway
POSSCON
 
PPTX
I Know It Was MEAN, But I Cut the Cord to LAMP Anyway
All Things Open
 
PDF
JavaScript Core
François Sarradin
 
PDF
GlueCon 2016 - Threading in JavaScript
Jonathan Baker
 
PDF
Promises are so passé - Tim Perry - Codemotion Milan 2016
Codemotion
 
PDF
Service worker - Offline Web
Bruno Oliveira
 
PDF
Promises look into the async future
slicejs
 
PDF
What's New in JavaScript
Dan Cohn
 
PDF
Asynchronous Programming with JavaScript
WebF
 
PPTX
Serverless in-action
Assaf Gannon
 
PDF
Going Serverless
Mattias Severson
 
KEY
Playing With Fire - An Introduction to Node.js
Mike Hagedorn
 
PPTX
Sufan presentation
Sufanhk
 
Asynchronous development in JavaScript
Amitai Barnea
 
Intro to Asynchronous Javascript
Garrett Welson
 
Async js - Nemetschek Presentaion @ HackBulgaria
HackBulgaria
 
The evolution of java script asynchronous calls
Huy Hoàng Phạm
 
Async JavaScript Unit Testing
Mihail Gaberov
 
Node.js
Mat Schaffer
 
Fundamental Node.js (Workshop bersama Front-end Developer GITS Indonesia, War...
GITS Indonesia
 
I Know It Was MEAN, But I Cut the Cord to LAMP Anyway
POSSCON
 
I Know It Was MEAN, But I Cut the Cord to LAMP Anyway
All Things Open
 
JavaScript Core
François Sarradin
 
GlueCon 2016 - Threading in JavaScript
Jonathan Baker
 
Promises are so passé - Tim Perry - Codemotion Milan 2016
Codemotion
 
Service worker - Offline Web
Bruno Oliveira
 
Promises look into the async future
slicejs
 
What's New in JavaScript
Dan Cohn
 
Asynchronous Programming with JavaScript
WebF
 
Serverless in-action
Assaf Gannon
 
Going Serverless
Mattias Severson
 
Playing With Fire - An Introduction to Node.js
Mike Hagedorn
 
Sufan presentation
Sufanhk
 
Ad

Recently uploaded (20)

PDF
Bitcoin+ Escalando sin concesiones - Parte 1
Fernando Paredes García
 
PDF
HR agent at Mediq: Lessons learned on Agent Builder & Maestro by Tacstone Tec...
UiPathCommunity
 
PDF
How ETL Control Logic Keeps Your Pipelines Safe and Reliable.pdf
Stryv Solutions Pvt. Ltd.
 
PDF
Alpha Altcoin Setup : TIA - 19th July 2025
CIFDAQ
 
PDF
introduction to computer hardware and sofeware
chauhanshraddha2007
 
PDF
Market Insight : ETH Dominance Returns
CIFDAQ
 
PDF
Market Wrap for 18th July 2025 by CIFDAQ
CIFDAQ
 
PPTX
Building and Operating a Private Cloud with CloudStack and LINBIT CloudStack ...
ShapeBlue
 
PDF
Integrating IIoT with SCADA in Oil & Gas A Technical Perspective.pdf
Rejig Digital
 
PDF
How Current Advanced Cyber Threats Transform Business Operation
Eryk Budi Pratama
 
PDF
Novus-Safe Pro: Brochure-What is Novus Safe Pro?.pdf
Novus Hi-Tech
 
PPTX
Agile Chennai 18-19 July 2025 | Emerging patterns in Agentic AI by Bharani Su...
AgileNetwork
 
PDF
The Past, Present & Future of Kenya's Digital Transformation
Moses Kemibaro
 
PDF
Women in Automation Presents: Reinventing Yourself — Bold Career Pivots That ...
DianaGray10
 
PDF
Arcee AI - building and working with small language models (06/25)
Julien SIMON
 
PPTX
The Yotta x CloudStack Advantage: Scalable, India-First Cloud
ShapeBlue
 
PPTX
AI Code Generation Risks (Ramkumar Dilli, CIO, Myridius)
Priyanka Aash
 
PDF
State-Dependent Conformal Perception Bounds for Neuro-Symbolic Verification
Ivan Ruchkin
 
PDF
NewMind AI Weekly Chronicles – July’25, Week III
NewMind AI
 
PDF
CIFDAQ'S Token Spotlight for 16th July 2025 - ALGORAND
CIFDAQ
 
Bitcoin+ Escalando sin concesiones - Parte 1
Fernando Paredes García
 
HR agent at Mediq: Lessons learned on Agent Builder & Maestro by Tacstone Tec...
UiPathCommunity
 
How ETL Control Logic Keeps Your Pipelines Safe and Reliable.pdf
Stryv Solutions Pvt. Ltd.
 
Alpha Altcoin Setup : TIA - 19th July 2025
CIFDAQ
 
introduction to computer hardware and sofeware
chauhanshraddha2007
 
Market Insight : ETH Dominance Returns
CIFDAQ
 
Market Wrap for 18th July 2025 by CIFDAQ
CIFDAQ
 
Building and Operating a Private Cloud with CloudStack and LINBIT CloudStack ...
ShapeBlue
 
Integrating IIoT with SCADA in Oil & Gas A Technical Perspective.pdf
Rejig Digital
 
How Current Advanced Cyber Threats Transform Business Operation
Eryk Budi Pratama
 
Novus-Safe Pro: Brochure-What is Novus Safe Pro?.pdf
Novus Hi-Tech
 
Agile Chennai 18-19 July 2025 | Emerging patterns in Agentic AI by Bharani Su...
AgileNetwork
 
The Past, Present & Future of Kenya's Digital Transformation
Moses Kemibaro
 
Women in Automation Presents: Reinventing Yourself — Bold Career Pivots That ...
DianaGray10
 
Arcee AI - building and working with small language models (06/25)
Julien SIMON
 
The Yotta x CloudStack Advantage: Scalable, India-First Cloud
ShapeBlue
 
AI Code Generation Risks (Ramkumar Dilli, CIO, Myridius)
Priyanka Aash
 
State-Dependent Conformal Perception Bounds for Neuro-Symbolic Verification
Ivan Ruchkin
 
NewMind AI Weekly Chronicles – July’25, Week III
NewMind AI
 
CIFDAQ'S Token Spotlight for 16th July 2025 - ALGORAND
CIFDAQ
 
Ad

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)