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

What's hot (20)

PDF
Service worker: discover the next web game changer
Sandro Paganotti
 
PDF
clara-rules
Ikuru Kanuma
 
KEY
Loadrunner
danwrong
 
PPTX
Intro to Ember.JS 2016
Sandino Núñez
 
PDF
Debugging War Stories & Strategies to Survive on RejectJS 2014
Johannes Weber
 
PDF
Containers & Dependency in Ember.js
Matthew Beale
 
PDF
Webgl para JavaScripters
gerbille
 
PDF
rx.js make async programming simpler
Alexander Mostovenko
 
PPTX
Workmanager PPTX
Himanshu Singh
 
PDF
The Peanut Butter Cup of Web-dev: Plack and single page web apps
John Anderson
 
PDF
Locarise,reagent and JavaScript Libraries
Ikuru Kanuma
 
PDF
Promise pattern
Sebastiaan Deckers
 
PDF
Analysing in depth work manager
bhatnagar.gaurav83
 
PDF
Svelte JS introduction
Mikhail Kuznetcov
 
KEY
CocoaHeads Toulouse - Guillaume Cerquant - UIView
CocoaHeads France
 
PDF
Introduction to AJAX In WordPress
Caldera Labs
 
PPTX
Pengenalan blaast platform sdk
Arief Bayu Purwanto
 
PDF
Integrating React.js with PHP projects
Ignacio Martín
 
PDF
Callbacks, promises, generators - asynchronous javascript
Łukasz Kużyński
 
PDF
Service worker API
Giorgio Natili
 
Service worker: discover the next web game changer
Sandro Paganotti
 
clara-rules
Ikuru Kanuma
 
Loadrunner
danwrong
 
Intro to Ember.JS 2016
Sandino Núñez
 
Debugging War Stories & Strategies to Survive on RejectJS 2014
Johannes Weber
 
Containers & Dependency in Ember.js
Matthew Beale
 
Webgl para JavaScripters
gerbille
 
rx.js make async programming simpler
Alexander Mostovenko
 
Workmanager PPTX
Himanshu Singh
 
The Peanut Butter Cup of Web-dev: Plack and single page web apps
John Anderson
 
Locarise,reagent and JavaScript Libraries
Ikuru Kanuma
 
Promise pattern
Sebastiaan Deckers
 
Analysing in depth work manager
bhatnagar.gaurav83
 
Svelte JS introduction
Mikhail Kuznetcov
 
CocoaHeads Toulouse - Guillaume Cerquant - UIView
CocoaHeads France
 
Introduction to AJAX In WordPress
Caldera Labs
 
Pengenalan blaast platform sdk
Arief Bayu Purwanto
 
Integrating React.js with PHP projects
Ignacio Martín
 
Callbacks, promises, generators - asynchronous javascript
Łukasz Kużyński
 
Service worker API
Giorgio Natili
 

Viewers also liked (15)

PPTX
Genetics and evolution
Tracy Adkins
 
DOC
Project 1 integration march 2015 (1)
howcyong1011
 
PPTX
Marketing research
Tet Velasco
 
PDF
Jonathan Rose CV PDF
Jonathan T.H. Rose,II
 
PPTX
Security Hole #18 - Cryptolocker Ransomware
Igor Beliaiev
 
DOC
Resume aman kumar
aman kumar
 
PDF
Idj topics big hero 6
howcyong1011
 
PPTX
Modular Train Control System menTCS
MEN Mikro Elektronik GmbH
 
PDF
Portfolio Petya M
Petja Mihaylova
 
PPTX
Baclofene Posologie
logicelemaling
 
PDF
Belize Destination Weddings – 11 Breathtaking Photos!
Chaa Creek Resort
 
PPTX
Animales salvaje
velenciasl
 
PPTX
S4 tarea4 PARIC
CarmenPallares
 
PPTX
Baclofene Posologie
logicelemaling
 
DOCX
RESUME CHRIS NEW
christopher isidro
 
Genetics and evolution
Tracy Adkins
 
Project 1 integration march 2015 (1)
howcyong1011
 
Marketing research
Tet Velasco
 
Jonathan Rose CV PDF
Jonathan T.H. Rose,II
 
Security Hole #18 - Cryptolocker Ransomware
Igor Beliaiev
 
Resume aman kumar
aman kumar
 
Idj topics big hero 6
howcyong1011
 
Modular Train Control System menTCS
MEN Mikro Elektronik GmbH
 
Portfolio Petya M
Petja Mihaylova
 
Baclofene Posologie
logicelemaling
 
Belize Destination Weddings – 11 Breathtaking Photos!
Chaa Creek Resort
 
Animales salvaje
velenciasl
 
S4 tarea4 PARIC
CarmenPallares
 
Baclofene Posologie
logicelemaling
 
RESUME CHRIS NEW
christopher isidro
 
Ad

Similar to Asynchronous Programming with JavaScript (20)

PDF
Sane Async Patterns
TrevorBurnham
 
PDF
Testing web APIs
FDConf
 
PDF
The Strange World of Javascript and all its little Asynchronous Beasts
Federico Galassi
 
PDF
The evolution of asynchronous JavaScript
Alessandro Cinelli (cirpo)
 
PDF
How to actually use promises - Jakob Mattsson, FishBrain
Codemotion Tel Aviv
 
PDF
Promises are so passé - Tim Perry - Codemotion Milan 2016
Codemotion
 
PPT
You promise?
IT Weekend
 
PPTX
Understanding Async/Await in Javascript
Hao Luo
 
PPTX
Async js
Alexandr Skachkov
 
PDF
4 mishchevskii - testing stage18-
Ievgenii Katsan
 
PPTX
The Promised Land (in Angular)
Domenic Denicola
 
PDF
Boom! Promises/A+ Was Born
Domenic Denicola
 
PDF
Async js - Nemetschek Presentaion @ HackBulgaria
HackBulgaria
 
PPTX
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
Domenic Denicola
 
PDF
Async History - javascript
Nishchit Dhanani
 
ODP
Node js
hazzaz
 
PDF
Javascript ES6 generators
RameshNair6
 
PDF
Utilizing Bluebird Promises
Nicholas van de Walle
 
PDF
node.js 실무 - node js in practice by Jesang Yoon
Jesang Yoon
 
PDF
Matthew Eernisse, NodeJs, .toster {webdev}
.toster
 
Sane Async Patterns
TrevorBurnham
 
Testing web APIs
FDConf
 
The Strange World of Javascript and all its little Asynchronous Beasts
Federico Galassi
 
The evolution of asynchronous JavaScript
Alessandro Cinelli (cirpo)
 
How to actually use promises - Jakob Mattsson, FishBrain
Codemotion Tel Aviv
 
Promises are so passé - Tim Perry - Codemotion Milan 2016
Codemotion
 
You promise?
IT Weekend
 
Understanding Async/Await in Javascript
Hao Luo
 
4 mishchevskii - testing stage18-
Ievgenii Katsan
 
The Promised Land (in Angular)
Domenic Denicola
 
Boom! Promises/A+ Was Born
Domenic Denicola
 
Async js - Nemetschek Presentaion @ HackBulgaria
HackBulgaria
 
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
Domenic Denicola
 
Async History - javascript
Nishchit Dhanani
 
Node js
hazzaz
 
Javascript ES6 generators
RameshNair6
 
Utilizing Bluebird Promises
Nicholas van de Walle
 
node.js 실무 - node js in practice by Jesang Yoon
Jesang Yoon
 
Matthew Eernisse, NodeJs, .toster {webdev}
.toster
 
Ad

More from WebF (9)

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

Recently uploaded (20)

PDF
[Newgen] NewgenONE Marvin Brochure 1.pdf
darshakparmar
 
PDF
LOOPS in C Programming Language - Technology
RishabhDwivedi43
 
PDF
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
PDF
Automating Feature Enrichment and Station Creation in Natural Gas Utility Net...
Safe Software
 
PPTX
Agentforce World Tour Toronto '25 - MCP with MuleSoft
Alexandra N. Martinez
 
PPTX
Designing_the_Future_AI_Driven_Product_Experiences_Across_Devices.pptx
presentifyai
 
PDF
CIFDAQ Market Wrap for the week of 4th July 2025
CIFDAQ
 
PDF
How do you fast track Agentic automation use cases discovery?
DianaGray10
 
PDF
POV_ Why Enterprises Need to Find Value in ZERO.pdf
darshakparmar
 
PDF
“Computer Vision at Sea: Automated Fish Tracking for Sustainable Fishing,” a ...
Edge AI and Vision Alliance
 
PDF
“NPU IP Hardware Shaped Through Software and Use-case Analysis,” a Presentati...
Edge AI and Vision Alliance
 
PDF
Transforming Utility Networks: Large-scale Data Migrations with FME
Safe Software
 
PPTX
COMPARISON OF RASTER ANALYSIS TOOLS OF QGIS AND ARCGIS
Sharanya Sarkar
 
PDF
The Rise of AI and IoT in Mobile App Tech.pdf
IMG Global Infotech
 
PDF
What’s my job again? Slides from Mark Simos talk at 2025 Tampa BSides
Mark Simos
 
PDF
UiPath DevConnect 2025: Agentic Automation Community User Group Meeting
DianaGray10
 
PPT
Ericsson LTE presentation SEMINAR 2010.ppt
npat3
 
PDF
The 2025 InfraRed Report - Redpoint Ventures
Razin Mustafiz
 
PPTX
Mastering ODC + Okta Configuration - Chennai OSUG
HathiMaryA
 
PPTX
Q2 FY26 Tableau User Group Leader Quarterly Call
lward7
 
[Newgen] NewgenONE Marvin Brochure 1.pdf
darshakparmar
 
LOOPS in C Programming Language - Technology
RishabhDwivedi43
 
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
Automating Feature Enrichment and Station Creation in Natural Gas Utility Net...
Safe Software
 
Agentforce World Tour Toronto '25 - MCP with MuleSoft
Alexandra N. Martinez
 
Designing_the_Future_AI_Driven_Product_Experiences_Across_Devices.pptx
presentifyai
 
CIFDAQ Market Wrap for the week of 4th July 2025
CIFDAQ
 
How do you fast track Agentic automation use cases discovery?
DianaGray10
 
POV_ Why Enterprises Need to Find Value in ZERO.pdf
darshakparmar
 
“Computer Vision at Sea: Automated Fish Tracking for Sustainable Fishing,” a ...
Edge AI and Vision Alliance
 
“NPU IP Hardware Shaped Through Software and Use-case Analysis,” a Presentati...
Edge AI and Vision Alliance
 
Transforming Utility Networks: Large-scale Data Migrations with FME
Safe Software
 
COMPARISON OF RASTER ANALYSIS TOOLS OF QGIS AND ARCGIS
Sharanya Sarkar
 
The Rise of AI and IoT in Mobile App Tech.pdf
IMG Global Infotech
 
What’s my job again? Slides from Mark Simos talk at 2025 Tampa BSides
Mark Simos
 
UiPath DevConnect 2025: Agentic Automation Community User Group Meeting
DianaGray10
 
Ericsson LTE presentation SEMINAR 2010.ppt
npat3
 
The 2025 InfraRed Report - Redpoint Ventures
Razin Mustafiz
 
Mastering ODC + Okta Configuration - Chennai OSUG
HathiMaryA
 
Q2 FY26 Tableau User Group Leader Quarterly Call
lward7
 

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.
  • 18. <web/F><web/F> Twitter: niloy_mondal84 Github: https://github.com/niloy Blog: https://github.com/niloy/blog/issues