SlideShare a Scribd company logo
<web/F><web/F>
Taming the Async Beast
By Niloy Mondal
@niloy_mondal84
<web/F><web/F>
Background
As a JS developer, async programming is a part of life.
Examples of Async APIs:
setTimeout, setInterval, addEventListener
XMLHttpRequest
CSS Animations
Database transactions in NodeJS
But no good tools to do async programming… till now
<web/F><web/F>
Callback Hell
Lets say we want to create a new user, upload photo and finally fetch all details of the user.
createUser(userDetails, function(response) {
if (response.success) {
var user = response.user;
uploadPhoto(user.id, photo, function(response) {
if (response.success) {
getUser(user.id, function(response) {...});
} else {
alert("Error: cannot upload photo");
}
});
} else {
alert("Error: cannot create user");
}
});
<web/F><web/F>
Problems
<web/F><web/F>
Promise
Rules are meant to broken, Promises are meant to be resolved.
Welcome `Promises` aka `Futures` aka `Continuation Monad` from functional programming.
Many initial implementations but now standardized. Now part of JS.
function setTimeoutP(delay) {
return new Promise(function(resolve, reject) {
setTimeout(resolve, delay);
});
}
setTimeoutP(2000).then(function() {
console.log("After 2 seconds");
});
<web/F><web/F>
Taming the Async Beast (Attempt 1)
var userId;
createUser(userDetails)
.then(function(user) {
userId = user.id;
return uploadPhoto(userId);
}).then(function() {
return getUser(userId);
}).then(function(userDetails) {
// user details fetched
}).catch(function() {
alert("Oops! Error occoured");
});
<web/F><web/F>
Benefits of using Promise
No pyramid of doom anymore, code is indented only to 1 level.
Code is somewhat sequential.
Execution flows from one `then` to another, top to bottom.
Clean error handling using `catch` similar to `try...catch` block.
<web/F><web/F>
Parallel execution using Promises
Usecase: Edit User Information page
var userDetailsPromise = getUser(userId);
var occupationValuesPromise = getOccupationValues();
Promise.all([userDetailsPromise, occupationValuesPromise])
.then(function(args) {
var userDetail = args[0];
var occupationValues = args[1];
// fill the UI elements here
});
<web/F><web/F>
Problems with Promise
Does solve the async problem to some extent but it still feels like a workaround/hack.
We have keep writing these `then` over and over for each async call.
If..else type conditional flow is hard.
For some complicated use cases, even Promises become an unreadable mess.
<web/F><web/F>
Can we do better?
.
<web/F><web/F>
Small introduction to Generators
What will be the output of the following code?
function* squares() {
var i = 1;
while(true) {
yield i * i;
i++;
}
}
var n = squares();
console.log(n.next().value);
console.log(n.next().value);
console.log(n.next().value);
<web/F><web/F>
Taming the Async Beast (Attempt 2)
Lets create a user, upload photo and fetch all details.
spawn(function*() {
try {
var user = yield createUser(userDetails);
yield uploadPhoto(user.id);
var userDetails = yield getUser(user.id);
// user details fetched
} catch(ex) {
alert("Oops! Error occoured");
}
});
<web/F><web/F>
Things to remember
• `spawn` function is a library code (http://taskjs.org/)
• Code is sequential even though we are doing async operations
• `try… catch` just works
• Requires `Promise` to work.The functions `createUser` must return a _Promise_ for this pattern to work.
The general rule of thumb is that `yield` can be used infront of functions that return Promise.
<web/F><web/F>
Parallel execution
spawn(function*() {
var values = yield [getUser(userId), getOccupationValues()];
var userDetailsPromise = values[0];
var occupationValuesPromise = values[1];
});
The way to think about this is, whatever you can pass to `Promise.all` can be passed to `yield`.
<web/F><web/F>
Serial Execution of Async Task (Unknown length)
Say you have a CSV file that you read line by line, extract values from each line and upload information by firing an API. The
execution of each API needs to be serial (one after another) because the data below depends on the data above it.
spawn(function*() {
var lines = fs.readFileSync("foo.csv", "utf-8").split("n");
for (var line of lines) {
yield pushRow(line);
}
});
<web/F><web/F>
Using Generators today
Generators are natively implemented in
• Chrome/Opera
• Firefox
• NodeJS(with harmony flag)
For other browsers, various transpilers can be used like Traceur or Babel. I personally use Tracuer.
<web/F><web/F>
Thank you
<web/F><web/F>
Twitter: niloy_mondal84
Github: https://github.com/niloy
Blog: https://github.com/niloy/blog/issues

More Related Content

PDF
Django for IoT: From hackathon to production (DjangoCon US)
PDF
History of jQuery
PDF
What's new in iOS9
PDF
PWA 應用 - 實現網站離線瀏覽
PPTX
Leap Motion Development (Rohan Puri)
PDF
Introduction to AngularJS
PDF
"Service Worker: Let Your Web App Feel Like a Native "
PDF
Build web application by express
Django for IoT: From hackathon to production (DjangoCon US)
History of jQuery
What's new in iOS9
PWA 應用 - 實現網站離線瀏覽
Leap Motion Development (Rohan Puri)
Introduction to AngularJS
"Service Worker: Let Your Web App Feel Like a Native "
Build web application by express

What's hot (20)

PDF
Service worker: discover the next web game changer
PDF
clara-rules
KEY
Loadrunner
PPTX
Intro to Ember.JS 2016
PDF
Debugging War Stories & Strategies to Survive on RejectJS 2014
PDF
Containers & Dependency in Ember.js
PDF
Webgl para JavaScripters
PDF
rx.js make async programming simpler
PPTX
Workmanager PPTX
PDF
The Peanut Butter Cup of Web-dev: Plack and single page web apps
PDF
Locarise,reagent and JavaScript Libraries
PDF
Promise pattern
PDF
Analysing in depth work manager
PDF
Svelte JS introduction
KEY
CocoaHeads Toulouse - Guillaume Cerquant - UIView
PDF
Introduction to AJAX In WordPress
PPTX
Pengenalan blaast platform sdk
PDF
Integrating React.js with PHP projects
PDF
Callbacks, promises, generators - asynchronous javascript
PDF
Service worker API
Service worker: discover the next web game changer
clara-rules
Loadrunner
Intro to Ember.JS 2016
Debugging War Stories & Strategies to Survive on RejectJS 2014
Containers & Dependency in Ember.js
Webgl para JavaScripters
rx.js make async programming simpler
Workmanager PPTX
The Peanut Butter Cup of Web-dev: Plack and single page web apps
Locarise,reagent and JavaScript Libraries
Promise pattern
Analysing in depth work manager
Svelte JS introduction
CocoaHeads Toulouse - Guillaume Cerquant - UIView
Introduction to AJAX In WordPress
Pengenalan blaast platform sdk
Integrating React.js with PHP projects
Callbacks, promises, generators - asynchronous javascript
Service worker API
Ad

Viewers also liked (15)

PPTX
Genetics and evolution
DOC
Project 1 integration march 2015 (1)
PPTX
Marketing research
PDF
Jonathan Rose CV PDF
PPTX
Security Hole #18 - Cryptolocker Ransomware
DOC
Resume aman kumar
PDF
Idj topics big hero 6
PPTX
Modular Train Control System menTCS
PDF
Portfolio Petya M
PPTX
Baclofene Posologie
PDF
Belize Destination Weddings – 11 Breathtaking Photos!
PPTX
Animales salvaje
PPTX
S4 tarea4 PARIC
PPTX
Baclofene Posologie
DOCX
RESUME CHRIS NEW
Genetics and evolution
Project 1 integration march 2015 (1)
Marketing research
Jonathan Rose CV PDF
Security Hole #18 - Cryptolocker Ransomware
Resume aman kumar
Idj topics big hero 6
Modular Train Control System menTCS
Portfolio Petya M
Baclofene Posologie
Belize Destination Weddings – 11 Breathtaking Photos!
Animales salvaje
S4 tarea4 PARIC
Baclofene Posologie
RESUME CHRIS NEW
Ad

Similar to Asynchronous Programming with JavaScript (20)

PDF
node.js practical guide to serverside javascript
PDF
soft-shake.ch - Hands on Node.js
PDF
WordPress Realtime - WordCamp São Paulo 2015
PDF
JavaScript para Graficos y Visualizacion de Datos
PDF
JavaScript para Graficos y Visualizacion de Datos - BogotaJS
PPT
WebGL: GPU acceleration for the open web
KEY
Mobile optimization
PDF
09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)
PDF
Secrets of JavaScript Libraries
PDF
Go Mobile with Apache Cordova, Zagreb 2014
PDF
JavaScript Libraries: The Big Picture
PDF
HTML5 - Daha Flash bir web?
PDF
Service Worker - Reliability bits
PDF
A More Flash Like Web?
PDF
Asynchronous Programming at Netflix
PDF
The Beauty of Java Script
PPTX
Cutting edge HTML5 API you can use today (by Bohdan Rusinka)
PDF
Web versus Native: round 1!
PPTX
Event-driven IO server-side JavaScript environment based on V8 Engine
KEY
JavaScript Growing Up
node.js practical guide to serverside javascript
soft-shake.ch - Hands on Node.js
WordPress Realtime - WordCamp São Paulo 2015
JavaScript para Graficos y Visualizacion de Datos
JavaScript para Graficos y Visualizacion de Datos - BogotaJS
WebGL: GPU acceleration for the open web
Mobile optimization
09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)
Secrets of JavaScript Libraries
Go Mobile with Apache Cordova, Zagreb 2014
JavaScript Libraries: The Big Picture
HTML5 - Daha Flash bir web?
Service Worker - Reliability bits
A More Flash Like Web?
Asynchronous Programming at Netflix
The Beauty of Java Script
Cutting edge HTML5 API you can use today (by Bohdan Rusinka)
Web versus Native: round 1!
Event-driven IO server-side JavaScript environment based on V8 Engine
JavaScript Growing Up

More from WebF (9)

PDF
IV - CSS architecture
PDF
III - Better angularjs
PDF
II - Angular.js app structure
PDF
2015 - Introduction to building enterprise web applications using Angular.js
PDF
II - Build Automation
PDF
Functional Programming with JavaScript
PDF
Keynote - WebF 2015
PDF
I - Front-end Spectrum
PDF
ECMAScript 6
IV - CSS architecture
III - Better angularjs
II - Angular.js app structure
2015 - Introduction to building enterprise web applications using Angular.js
II - Build Automation
Functional Programming with JavaScript
Keynote - WebF 2015
I - Front-end Spectrum
ECMAScript 6

Recently uploaded (20)

PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PPTX
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication
PDF
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
PDF
Spectral efficient network and resource selection model in 5G networks
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
DOCX
The AUB Centre for AI in Media Proposal.docx
PDF
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
PDF
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
PDF
KodekX | Application Modernization Development
PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
PDF
Encapsulation theory and applications.pdf
PDF
cuic standard and advanced reporting.pdf
PPTX
A Presentation on Artificial Intelligence
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PDF
NewMind AI Monthly Chronicles - July 2025
PDF
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
PDF
Electronic commerce courselecture one. Pdf
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PDF
Chapter 3 Spatial Domain Image Processing.pdf
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
Dropbox Q2 2025 Financial Results & Investor Presentation
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
Spectral efficient network and resource selection model in 5G networks
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
The AUB Centre for AI in Media Proposal.docx
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
KodekX | Application Modernization Development
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
Encapsulation theory and applications.pdf
cuic standard and advanced reporting.pdf
A Presentation on Artificial Intelligence
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
NewMind AI Monthly Chronicles - July 2025
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
Electronic commerce courselecture one. Pdf
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
Chapter 3 Spatial Domain Image Processing.pdf
The Rise and Fall of 3GPP – Time for a Sabbatical?

Asynchronous Programming with JavaScript

  • 1. <web/F><web/F> Taming the Async Beast By Niloy Mondal @niloy_mondal84
  • 2. <web/F><web/F> Background As a JS developer, async programming is a part of life. Examples of Async APIs: setTimeout, setInterval, addEventListener XMLHttpRequest CSS Animations Database transactions in NodeJS But no good tools to do async programming… till now
  • 3. <web/F><web/F> Callback Hell Lets say we want to create a new user, upload photo and finally fetch all details of the user. createUser(userDetails, function(response) { if (response.success) { var user = response.user; uploadPhoto(user.id, photo, function(response) { if (response.success) { getUser(user.id, function(response) {...}); } else { alert("Error: cannot upload photo"); } }); } else { alert("Error: cannot create user"); } });
  • 5. <web/F><web/F> Promise Rules are meant to broken, Promises are meant to be resolved. Welcome `Promises` aka `Futures` aka `Continuation Monad` from functional programming. Many initial implementations but now standardized. Now part of JS. function setTimeoutP(delay) { return new Promise(function(resolve, reject) { setTimeout(resolve, delay); }); } setTimeoutP(2000).then(function() { console.log("After 2 seconds"); });
  • 6. <web/F><web/F> Taming the Async Beast (Attempt 1) var userId; createUser(userDetails) .then(function(user) { userId = user.id; return uploadPhoto(userId); }).then(function() { return getUser(userId); }).then(function(userDetails) { // user details fetched }).catch(function() { alert("Oops! Error occoured"); });
  • 7. <web/F><web/F> Benefits of using Promise No pyramid of doom anymore, code is indented only to 1 level. Code is somewhat sequential. Execution flows from one `then` to another, top to bottom. Clean error handling using `catch` similar to `try...catch` block.
  • 8. <web/F><web/F> Parallel execution using Promises Usecase: Edit User Information page var userDetailsPromise = getUser(userId); var occupationValuesPromise = getOccupationValues(); Promise.all([userDetailsPromise, occupationValuesPromise]) .then(function(args) { var userDetail = args[0]; var occupationValues = args[1]; // fill the UI elements here });
  • 9. <web/F><web/F> Problems with Promise Does solve the async problem to some extent but it still feels like a workaround/hack. We have keep writing these `then` over and over for each async call. If..else type conditional flow is hard. For some complicated use cases, even Promises become an unreadable mess.
  • 11. <web/F><web/F> Small introduction to Generators What will be the output of the following code? function* squares() { var i = 1; while(true) { yield i * i; i++; } } var n = squares(); console.log(n.next().value); console.log(n.next().value); console.log(n.next().value);
  • 12. <web/F><web/F> Taming the Async Beast (Attempt 2) Lets create a user, upload photo and fetch all details. spawn(function*() { try { var user = yield createUser(userDetails); yield uploadPhoto(user.id); var userDetails = yield getUser(user.id); // user details fetched } catch(ex) { alert("Oops! Error occoured"); } });
  • 13. <web/F><web/F> Things to remember • `spawn` function is a library code (http://taskjs.org/) • Code is sequential even though we are doing async operations • `try… catch` just works • Requires `Promise` to work.The functions `createUser` must return a _Promise_ for this pattern to work. The general rule of thumb is that `yield` can be used infront of functions that return Promise.
  • 14. <web/F><web/F> Parallel execution spawn(function*() { var values = yield [getUser(userId), getOccupationValues()]; var userDetailsPromise = values[0]; var occupationValuesPromise = values[1]; }); The way to think about this is, whatever you can pass to `Promise.all` can be passed to `yield`.
  • 15. <web/F><web/F> Serial Execution of Async Task (Unknown length) Say you have a CSV file that you read line by line, extract values from each line and upload information by firing an API. The execution of each API needs to be serial (one after another) because the data below depends on the data above it. spawn(function*() { var lines = fs.readFileSync("foo.csv", "utf-8").split("n"); for (var line of lines) { yield pushRow(line); } });
  • 16. <web/F><web/F> Using Generators today Generators are natively implemented in • Chrome/Opera • Firefox • NodeJS(with harmony flag) For other browsers, various transpilers can be used like Traceur or Babel. I personally use Tracuer.