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
Sane Async Patterns
PDF
Testing web APIs
PDF
The Strange World of Javascript and all its little Asynchronous Beasts
PDF
The evolution of asynchronous JavaScript
PDF
How to actually use promises - Jakob Mattsson, FishBrain
PDF
Promises are so passé - Tim Perry - Codemotion Milan 2016
PPT
You promise?
PPTX
Understanding Async/Await in Javascript
PPTX
PDF
4 mishchevskii - testing stage18-
PPTX
The Promised Land (in Angular)
PDF
Boom! Promises/A+ Was Born
PDF
Async js - Nemetschek Presentaion @ HackBulgaria
PPTX
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
PDF
Async History - javascript
ODP
Node js
PDF
Javascript ES6 generators
PDF
Utilizing Bluebird Promises
PDF
node.js 실무 - node js in practice by Jesang Yoon
PDF
Matthew Eernisse, NodeJs, .toster {webdev}
Sane Async Patterns
Testing web APIs
The Strange World of Javascript and all its little Asynchronous Beasts
The evolution of asynchronous JavaScript
How to actually use promises - Jakob Mattsson, FishBrain
Promises are so passé - Tim Perry - Codemotion Milan 2016
You promise?
Understanding Async/Await in Javascript
4 mishchevskii - testing stage18-
The Promised Land (in Angular)
Boom! Promises/A+ Was Born
Async js - Nemetschek Presentaion @ HackBulgaria
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
Async History - javascript
Node js
Javascript ES6 generators
Utilizing Bluebird Promises
node.js 실무 - node js in practice by Jesang Yoon
Matthew Eernisse, NodeJs, .toster {webdev}

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
Chapter 2 Digital Image Fundamentals.pdf
PDF
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
PPTX
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication
PPTX
ABU RAUP TUGAS TIK kelas 8 hjhgjhgg.pptx
PDF
KodekX | Application Modernization Development
PDF
Automating ArcGIS Content Discovery with FME: A Real World Use Case
PDF
Reimagining Insurance: Connected Data for Confident Decisions.pdf
PDF
NewMind AI Monthly Chronicles - July 2025
PDF
NewMind AI Weekly Chronicles - August'25 Week I
PDF
Cloud-Migration-Best-Practices-A-Practical-Guide-to-AWS-Azure-and-Google-Clou...
PDF
A Day in the Life of Location Data - Turning Where into How.pdf
PDF
CIFDAQ's Market Wrap: Ethereum Leads, Bitcoin Lags, Institutions Shift
PDF
Transforming Manufacturing operations through Intelligent Integrations
PDF
Event Presentation Google Cloud Next Extended 2025
PDF
Dell Pro 14 Plus: Be better prepared for what’s coming
PDF
CIFDAQ's Token Spotlight: SKY - A Forgotten Giant's Comeback?
PDF
Sensors and Actuators in IoT Systems using pdf
PDF
GamePlan Trading System Review: Professional Trader's Honest Take
PDF
Enable Enterprise-Ready Security on IBM i Systems.pdf
PDF
Google’s NotebookLM Unveils Video Overviews
Chapter 2 Digital Image Fundamentals.pdf
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication
ABU RAUP TUGAS TIK kelas 8 hjhgjhgg.pptx
KodekX | Application Modernization Development
Automating ArcGIS Content Discovery with FME: A Real World Use Case
Reimagining Insurance: Connected Data for Confident Decisions.pdf
NewMind AI Monthly Chronicles - July 2025
NewMind AI Weekly Chronicles - August'25 Week I
Cloud-Migration-Best-Practices-A-Practical-Guide-to-AWS-Azure-and-Google-Clou...
A Day in the Life of Location Data - Turning Where into How.pdf
CIFDAQ's Market Wrap: Ethereum Leads, Bitcoin Lags, Institutions Shift
Transforming Manufacturing operations through Intelligent Integrations
Event Presentation Google Cloud Next Extended 2025
Dell Pro 14 Plus: Be better prepared for what’s coming
CIFDAQ's Token Spotlight: SKY - A Forgotten Giant's Comeback?
Sensors and Actuators in IoT Systems using pdf
GamePlan Trading System Review: Professional Trader's Honest Take
Enable Enterprise-Ready Security on IBM i Systems.pdf
Google’s NotebookLM Unveils Video Overviews

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.