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)

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

Viewers also liked (15)

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

Similar to Asynchronous Programming with JavaScript (20)

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

More from WebF (9)

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

Recently uploaded (20)

ELNL2025 - Unlocking the Power of Sensitivity Labels - A Comprehensive Guide....
ELNL2025 - Unlocking the Power of Sensitivity Labels - A Comprehensive Guide....ELNL2025 - Unlocking the Power of Sensitivity Labels - A Comprehensive Guide....
ELNL2025 - Unlocking the Power of Sensitivity Labels - A Comprehensive Guide....
Jasper Oosterveld
 
MCP vs A2A vs ACP: Choosing the Right Protocol | Bluebash
MCP vs A2A vs ACP: Choosing the Right Protocol | BluebashMCP vs A2A vs ACP: Choosing the Right Protocol | Bluebash
MCP vs A2A vs ACP: Choosing the Right Protocol | Bluebash
Bluebash
 
Your startup on AWS - How to architect and maintain a Lean and Mean account
Your startup on AWS - How to architect and maintain a Lean and Mean accountYour startup on AWS - How to architect and maintain a Lean and Mean account
Your startup on AWS - How to architect and maintain a Lean and Mean account
angelo60207
 
What is Oracle EPM A Guide to Oracle EPM Cloud Everything You Need to Know
What is Oracle EPM A Guide to Oracle EPM Cloud Everything You Need to KnowWhat is Oracle EPM A Guide to Oracle EPM Cloud Everything You Need to Know
What is Oracle EPM A Guide to Oracle EPM Cloud Everything You Need to Know
SMACT Works
 
Oracle Cloud Infrastructure AI Foundations
Oracle Cloud Infrastructure AI FoundationsOracle Cloud Infrastructure AI Foundations
Oracle Cloud Infrastructure AI Foundations
VICTOR MAESTRE RAMIREZ
 
National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...
National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...
National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...
Safe Software
 
Introduction to Internet of things .ppt.
Introduction to Internet of things .ppt.Introduction to Internet of things .ppt.
Introduction to Internet of things .ppt.
hok12341073
 
Soulmaite review - Find Real AI soulmate review
Soulmaite review - Find Real AI soulmate reviewSoulmaite review - Find Real AI soulmate review
Soulmaite review - Find Real AI soulmate review
Soulmaite
 
vertical-cnc-processing-centers-drillteq-v-200-en.pdf
vertical-cnc-processing-centers-drillteq-v-200-en.pdfvertical-cnc-processing-centers-drillteq-v-200-en.pdf
vertical-cnc-processing-centers-drillteq-v-200-en.pdf
AmirStern2
 
Murdledescargadarkweb.pdfvolumen1 100 elementary
Murdledescargadarkweb.pdfvolumen1 100 elementaryMurdledescargadarkweb.pdfvolumen1 100 elementary
Murdledescargadarkweb.pdfvolumen1 100 elementary
JorgeSemperteguiMont
 
Data Virtualization: Bringing the Power of FME to Any Application
Data Virtualization: Bringing the Power of FME to Any ApplicationData Virtualization: Bringing the Power of FME to Any Application
Data Virtualization: Bringing the Power of FME to Any Application
Safe Software
 
Boosting MySQL with Vector Search -THE VECTOR SEARCH CONFERENCE 2025 .pdf
Boosting MySQL with Vector Search -THE VECTOR SEARCH CONFERENCE 2025 .pdfBoosting MySQL with Vector Search -THE VECTOR SEARCH CONFERENCE 2025 .pdf
Boosting MySQL with Vector Search -THE VECTOR SEARCH CONFERENCE 2025 .pdf
Alkin Tezuysal
 
End-to-end Assurance for SD-WAN & SASE with ThousandEyes
End-to-end Assurance for SD-WAN & SASE with ThousandEyesEnd-to-end Assurance for SD-WAN & SASE with ThousandEyes
End-to-end Assurance for SD-WAN & SASE with ThousandEyes
ThousandEyes
 
Establish Visibility and Manage Risk in the Supply Chain with Anchore SBOM
Establish Visibility and Manage Risk in the Supply Chain with Anchore SBOMEstablish Visibility and Manage Risk in the Supply Chain with Anchore SBOM
Establish Visibility and Manage Risk in the Supply Chain with Anchore SBOM
Anchore
 
7 Salesforce Data Cloud Best Practices.pdf
7 Salesforce Data Cloud Best Practices.pdf7 Salesforce Data Cloud Best Practices.pdf
7 Salesforce Data Cloud Best Practices.pdf
Minuscule Technologies
 
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Anish Kumar
 
Improving Developer Productivity With DORA, SPACE, and DevEx
Improving Developer Productivity With DORA, SPACE, and DevExImproving Developer Productivity With DORA, SPACE, and DevEx
Improving Developer Productivity With DORA, SPACE, and DevEx
Justin Reock
 
Dancing with AI - A Developer's Journey.pptx
Dancing with AI - A Developer's Journey.pptxDancing with AI - A Developer's Journey.pptx
Dancing with AI - A Developer's Journey.pptx
Elliott Richmond
 
FCF- Getting Started in Cybersecurity 3.0
FCF- Getting Started in Cybersecurity 3.0FCF- Getting Started in Cybersecurity 3.0
FCF- Getting Started in Cybersecurity 3.0
RodrigoMori7
 
Jeremy Millul - A Talented Software Developer
Jeremy Millul - A Talented Software DeveloperJeremy Millul - A Talented Software Developer
Jeremy Millul - A Talented Software Developer
Jeremy Millul
 
ELNL2025 - Unlocking the Power of Sensitivity Labels - A Comprehensive Guide....
ELNL2025 - Unlocking the Power of Sensitivity Labels - A Comprehensive Guide....ELNL2025 - Unlocking the Power of Sensitivity Labels - A Comprehensive Guide....
ELNL2025 - Unlocking the Power of Sensitivity Labels - A Comprehensive Guide....
Jasper Oosterveld
 
MCP vs A2A vs ACP: Choosing the Right Protocol | Bluebash
MCP vs A2A vs ACP: Choosing the Right Protocol | BluebashMCP vs A2A vs ACP: Choosing the Right Protocol | Bluebash
MCP vs A2A vs ACP: Choosing the Right Protocol | Bluebash
Bluebash
 
Your startup on AWS - How to architect and maintain a Lean and Mean account
Your startup on AWS - How to architect and maintain a Lean and Mean accountYour startup on AWS - How to architect and maintain a Lean and Mean account
Your startup on AWS - How to architect and maintain a Lean and Mean account
angelo60207
 
What is Oracle EPM A Guide to Oracle EPM Cloud Everything You Need to Know
What is Oracle EPM A Guide to Oracle EPM Cloud Everything You Need to KnowWhat is Oracle EPM A Guide to Oracle EPM Cloud Everything You Need to Know
What is Oracle EPM A Guide to Oracle EPM Cloud Everything You Need to Know
SMACT Works
 
Oracle Cloud Infrastructure AI Foundations
Oracle Cloud Infrastructure AI FoundationsOracle Cloud Infrastructure AI Foundations
Oracle Cloud Infrastructure AI Foundations
VICTOR MAESTRE RAMIREZ
 
National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...
National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...
National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...
Safe Software
 
Introduction to Internet of things .ppt.
Introduction to Internet of things .ppt.Introduction to Internet of things .ppt.
Introduction to Internet of things .ppt.
hok12341073
 
Soulmaite review - Find Real AI soulmate review
Soulmaite review - Find Real AI soulmate reviewSoulmaite review - Find Real AI soulmate review
Soulmaite review - Find Real AI soulmate review
Soulmaite
 
vertical-cnc-processing-centers-drillteq-v-200-en.pdf
vertical-cnc-processing-centers-drillteq-v-200-en.pdfvertical-cnc-processing-centers-drillteq-v-200-en.pdf
vertical-cnc-processing-centers-drillteq-v-200-en.pdf
AmirStern2
 
Murdledescargadarkweb.pdfvolumen1 100 elementary
Murdledescargadarkweb.pdfvolumen1 100 elementaryMurdledescargadarkweb.pdfvolumen1 100 elementary
Murdledescargadarkweb.pdfvolumen1 100 elementary
JorgeSemperteguiMont
 
Data Virtualization: Bringing the Power of FME to Any Application
Data Virtualization: Bringing the Power of FME to Any ApplicationData Virtualization: Bringing the Power of FME to Any Application
Data Virtualization: Bringing the Power of FME to Any Application
Safe Software
 
Boosting MySQL with Vector Search -THE VECTOR SEARCH CONFERENCE 2025 .pdf
Boosting MySQL with Vector Search -THE VECTOR SEARCH CONFERENCE 2025 .pdfBoosting MySQL with Vector Search -THE VECTOR SEARCH CONFERENCE 2025 .pdf
Boosting MySQL with Vector Search -THE VECTOR SEARCH CONFERENCE 2025 .pdf
Alkin Tezuysal
 
End-to-end Assurance for SD-WAN & SASE with ThousandEyes
End-to-end Assurance for SD-WAN & SASE with ThousandEyesEnd-to-end Assurance for SD-WAN & SASE with ThousandEyes
End-to-end Assurance for SD-WAN & SASE with ThousandEyes
ThousandEyes
 
Establish Visibility and Manage Risk in the Supply Chain with Anchore SBOM
Establish Visibility and Manage Risk in the Supply Chain with Anchore SBOMEstablish Visibility and Manage Risk in the Supply Chain with Anchore SBOM
Establish Visibility and Manage Risk in the Supply Chain with Anchore SBOM
Anchore
 
7 Salesforce Data Cloud Best Practices.pdf
7 Salesforce Data Cloud Best Practices.pdf7 Salesforce Data Cloud Best Practices.pdf
7 Salesforce Data Cloud Best Practices.pdf
Minuscule Technologies
 
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Anish Kumar
 
Improving Developer Productivity With DORA, SPACE, and DevEx
Improving Developer Productivity With DORA, SPACE, and DevExImproving Developer Productivity With DORA, SPACE, and DevEx
Improving Developer Productivity With DORA, SPACE, and DevEx
Justin Reock
 
Dancing with AI - A Developer's Journey.pptx
Dancing with AI - A Developer's Journey.pptxDancing with AI - A Developer's Journey.pptx
Dancing with AI - A Developer's Journey.pptx
Elliott Richmond
 
FCF- Getting Started in Cybersecurity 3.0
FCF- Getting Started in Cybersecurity 3.0FCF- Getting Started in Cybersecurity 3.0
FCF- Getting Started in Cybersecurity 3.0
RodrigoMori7
 
Jeremy Millul - A Talented Software Developer
Jeremy Millul - A Talented Software DeveloperJeremy Millul - A Talented Software Developer
Jeremy Millul - A Talented Software Developer
Jeremy Millul
 

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.