SlideShare a Scribd company logo
ASYNCHRONOUS CODING IN NODEJS 
CALLBACKS AND CONTROL FLOW 
Thomas Roch, Formedix Ltd
NODE'S EXPERIENCE ANYONE?
WHAT IS NODEJS 
Node.js uses an event-driven, non-blocking I/O model 
that makes it lightweight and efficient, perfect for data-intensive 
real-time applications that run across 
distributed devices. 
Event driven => event listeners 
Non-blocking IO => callbacks 
= 
ASYNCHRONOUS
BEFORE WE START 
Non-blocking functions take callbacks (last argument) of two forms: 
function (err, res) { 
// Do something 
} 
function (res) { 
// Do something 
}
WE ARE GOING TO TALK ABOUT 
Callback hell 
Inversion of control 
Control flow 
Promises 
Thunks 
Generators (or iterators)
EXAMPLE 
A wish list server where one can: 
Create a whish list 
Add items to a whish list 
Retrieve the content of a whishlist 
Code available here
REST API 
POST /whishList 
POST /whishList/{id} 
GET /whishList/{id}
WHAT WE AIM FOR
WHAT WE ARE GOING TO DO FIRST
EXAMPLE A 
A mix of events and non-blocking 
functions with http.request() for: 
Creating a list 
Adding an item to a list 
Getting a list's content
EXAMPLE B: 
Turn this mess into functions accepting callbacks 
With 3 functions: createList, addItem, getList... 
...we are creating a nice "callback hell" aka "callback pyramid"
ASYNC TO THE RESCUE 
First control flow example with https://github.com/caolan/async 
async.series() 
async.waterfall() 
async.parallel() 
Works with any non-blocking function "the node way"
OK... WE'VE DONE STUFF IN PARALLEL 
Does this look good? 
What about avoiding iversion of control?
EXAMPLE C: USING PROMISES 
ES6 feature but implementations available in ES5 
Returns a deferred result (success or error) accessed using .then(): 
createList , addItem , 
getList 
Control flow using q 
: chaining promises, error propagation, Q.all... 
Compatible with Node API functions using Q.nfcall()
BEFORE EXAMPLE D 
Generators (or iterators)! What are they? 
function* () { 
yield 1; 
return 2; 
}
EXAMPLE D: USING GENERATORS 
What about yielding a promise or a thunk? a what? 
Control flow using co 
// The node way 
phoneMyPal(number, function (err, res) { 
console.log('hi'); 
}); 
// A thunk 
phoneMyPal(number)(function (err, res) { 
console.log('hi'); 
}); 
Let's thunkify createList, addItem, getList
EXAMPLE D: USING GENERATORS 
works with thunks or promises 
co 
Compatible with Node API using 
thunkify 
Non-blocking code looking like it is not! 
Used by koa.js 
, a web application framework
QUESTIONS

More Related Content

What's hot (20)

PPTX
The Promised Land (in Angular)
Domenic Denicola
 
PDF
JavaScript Promise
Joseph Chiang
 
PDF
$q and Promises in AngularJS
a_sharif
 
PDF
Promise pattern
Sebastiaan Deckers
 
PPTX
JavaScript Promises
L&T Technology Services Limited
 
PDF
Node.js: Continuation-Local-Storage and the Magic of AsyncListener
Islam Sharabash
 
PDF
Getting Comfortable with JS Promises
Asa Kusuma
 
PDF
Avoiding callback hell with promises
TorontoNodeJS
 
PDF
Practical JavaScript Promises
Asa Kusuma
 
PDF
How to send gzipped requests with boto3
Luciano Mammino
 
PDF
CLS & asyncListener: asynchronous observability for Node.js
Forrest Norvell
 
PPTX
Reactive Java (33rd Degree)
Tomasz Kowalczewski
 
PDF
JavaScript Promises
Derek Willian Stavis
 
PPTX
Behind modern concurrency primitives
Bartosz Sypytkowski
 
PDF
JavaScript Promises
Tomasz Bak
 
PDF
The evolution of asynchronous javascript
Alessandro Cinelli (cirpo)
 
PDF
JavaScript promise
eslam_me
 
PDF
Asynchronní programování
PeckaDesign.cz
 
PPTX
Java Script Promise
Alok Guha
 
PDF
Asynchronous Programming FTW! 2 (with AnyEvent)
xSawyer
 
The Promised Land (in Angular)
Domenic Denicola
 
JavaScript Promise
Joseph Chiang
 
$q and Promises in AngularJS
a_sharif
 
Promise pattern
Sebastiaan Deckers
 
JavaScript Promises
L&T Technology Services Limited
 
Node.js: Continuation-Local-Storage and the Magic of AsyncListener
Islam Sharabash
 
Getting Comfortable with JS Promises
Asa Kusuma
 
Avoiding callback hell with promises
TorontoNodeJS
 
Practical JavaScript Promises
Asa Kusuma
 
How to send gzipped requests with boto3
Luciano Mammino
 
CLS & asyncListener: asynchronous observability for Node.js
Forrest Norvell
 
Reactive Java (33rd Degree)
Tomasz Kowalczewski
 
JavaScript Promises
Derek Willian Stavis
 
Behind modern concurrency primitives
Bartosz Sypytkowski
 
JavaScript Promises
Tomasz Bak
 
The evolution of asynchronous javascript
Alessandro Cinelli (cirpo)
 
JavaScript promise
eslam_me
 
Asynchronní programování
PeckaDesign.cz
 
Java Script Promise
Alok Guha
 
Asynchronous Programming FTW! 2 (with AnyEvent)
xSawyer
 

Similar to Callbacks and control flow in Node js (20)

PDF
Release with confidence
John Congdon
 
PDF
Programming Sideways: Asynchronous Techniques for Android
Emanuele Di Saverio
 
PDF
"Applied Enterprise Metaprogramming in JavaScript", Vladyslav Dukhin
Fwdays
 
PDF
Lagom in Practice
JWORKS powered by Ordina
 
ODP
Lucio Grenzi - Building serverless applications on the Apache OpenWhisk platf...
Codemotion
 
ODP
Building serverless application on the Apache Openwhisk platform
Lucio Grenzi
 
PDF
Asynchronous development in JavaScript
Amitai Barnea
 
PDF
BUILDING APPS WITH ASYNCIO
Mykola Novik
 
ODP
Scala Future & Promises
Knoldus Inc.
 
PDF
Advanced JavaScript - Internship Presentation - Week6
Devang Garach
 
PPTX
4Developers 2015: Programowanie synchroniczne i asynchroniczne - dwa światy k...
PROIDEA
 
PPTX
JavaScript (without DOM)
Piyush Katariya
 
PDF
Building a Serverless company with Node.js, React and the Serverless Framewor...
Luciano Mammino
 
PDF
Promises - Asynchronous Control Flow
Henrique Barcelos
 
PDF
What is new in java 8 concurrency
kshanth2101
 
PPTX
Introduction to nsubstitute
Suresh Loganatha
 
PPTX
Inside Logic Apps
BizTalk360
 
PDF
Faster PHP apps using Queues and Workers
Richard Baker
 
PPTX
Reactive Java: Promises and Streams with Reakt (JavaOne talk 2016)
Rick Hightower
 
PPTX
Reactive Java: Promises and Streams with Reakt (JavaOne Talk 2016)
Rick Hightower
 
Release with confidence
John Congdon
 
Programming Sideways: Asynchronous Techniques for Android
Emanuele Di Saverio
 
"Applied Enterprise Metaprogramming in JavaScript", Vladyslav Dukhin
Fwdays
 
Lagom in Practice
JWORKS powered by Ordina
 
Lucio Grenzi - Building serverless applications on the Apache OpenWhisk platf...
Codemotion
 
Building serverless application on the Apache Openwhisk platform
Lucio Grenzi
 
Asynchronous development in JavaScript
Amitai Barnea
 
BUILDING APPS WITH ASYNCIO
Mykola Novik
 
Scala Future & Promises
Knoldus Inc.
 
Advanced JavaScript - Internship Presentation - Week6
Devang Garach
 
4Developers 2015: Programowanie synchroniczne i asynchroniczne - dwa światy k...
PROIDEA
 
JavaScript (without DOM)
Piyush Katariya
 
Building a Serverless company with Node.js, React and the Serverless Framewor...
Luciano Mammino
 
Promises - Asynchronous Control Flow
Henrique Barcelos
 
What is new in java 8 concurrency
kshanth2101
 
Introduction to nsubstitute
Suresh Loganatha
 
Inside Logic Apps
BizTalk360
 
Faster PHP apps using Queues and Workers
Richard Baker
 
Reactive Java: Promises and Streams with Reakt (JavaOne talk 2016)
Rick Hightower
 
Reactive Java: Promises and Streams with Reakt (JavaOne Talk 2016)
Rick Hightower
 
Ad

Recently uploaded (20)

PDF
TrustArc Webinar - Navigating Data Privacy in LATAM: Laws, Trends, and Compli...
TrustArc
 
PPTX
Agile Chennai 18-19 July 2025 | Workshop - Enhancing Agile Collaboration with...
AgileNetwork
 
PDF
GDG Cloud Munich - Intro - Luiz Carneiro - #BuildWithAI - July - Abdel.pdf
Luiz Carneiro
 
PPTX
IT Runs Better with ThousandEyes AI-driven Assurance
ThousandEyes
 
PDF
MASTERDECK GRAPHSUMMIT SYDNEY (Public).pdf
Neo4j
 
PPTX
Applied-Statistics-Mastering-Data-Driven-Decisions.pptx
parmaryashparmaryash
 
PDF
Per Axbom: The spectacular lies of maps
Nexer Digital
 
PDF
CIFDAQ's Market Wrap : Bears Back in Control?
CIFDAQ
 
PDF
SalesForce Managed Services Benefits (1).pdf
TechForce Services
 
PDF
Integrating IIoT with SCADA in Oil & Gas A Technical Perspective.pdf
Rejig Digital
 
PDF
Generative AI vs Predictive AI-The Ultimate Comparison Guide
Lily Clark
 
PPTX
AI Code Generation Risks (Ramkumar Dilli, CIO, Myridius)
Priyanka Aash
 
PPTX
python advanced data structure dictionary with examples python advanced data ...
sprasanna11
 
PDF
Economic Impact of Data Centres to the Malaysian Economy
flintglobalapac
 
PDF
visibel.ai Company Profile – Real-Time AI Solution for CCTV
visibelaiproject
 
PDF
The Future of Mobile Is Context-Aware—Are You Ready?
iProgrammer Solutions Private Limited
 
PDF
Lecture A - AI Workflows for Banking.pdf
Dr. LAM Yat-fai (林日辉)
 
PPTX
Agentic AI in Healthcare Driving the Next Wave of Digital Transformation
danielle hunter
 
PDF
Build with AI and GDG Cloud Bydgoszcz- ADK .pdf
jaroslawgajewski1
 
PPTX
Machine Learning Benefits Across Industries
SynapseIndia
 
TrustArc Webinar - Navigating Data Privacy in LATAM: Laws, Trends, and Compli...
TrustArc
 
Agile Chennai 18-19 July 2025 | Workshop - Enhancing Agile Collaboration with...
AgileNetwork
 
GDG Cloud Munich - Intro - Luiz Carneiro - #BuildWithAI - July - Abdel.pdf
Luiz Carneiro
 
IT Runs Better with ThousandEyes AI-driven Assurance
ThousandEyes
 
MASTERDECK GRAPHSUMMIT SYDNEY (Public).pdf
Neo4j
 
Applied-Statistics-Mastering-Data-Driven-Decisions.pptx
parmaryashparmaryash
 
Per Axbom: The spectacular lies of maps
Nexer Digital
 
CIFDAQ's Market Wrap : Bears Back in Control?
CIFDAQ
 
SalesForce Managed Services Benefits (1).pdf
TechForce Services
 
Integrating IIoT with SCADA in Oil & Gas A Technical Perspective.pdf
Rejig Digital
 
Generative AI vs Predictive AI-The Ultimate Comparison Guide
Lily Clark
 
AI Code Generation Risks (Ramkumar Dilli, CIO, Myridius)
Priyanka Aash
 
python advanced data structure dictionary with examples python advanced data ...
sprasanna11
 
Economic Impact of Data Centres to the Malaysian Economy
flintglobalapac
 
visibel.ai Company Profile – Real-Time AI Solution for CCTV
visibelaiproject
 
The Future of Mobile Is Context-Aware—Are You Ready?
iProgrammer Solutions Private Limited
 
Lecture A - AI Workflows for Banking.pdf
Dr. LAM Yat-fai (林日辉)
 
Agentic AI in Healthcare Driving the Next Wave of Digital Transformation
danielle hunter
 
Build with AI and GDG Cloud Bydgoszcz- ADK .pdf
jaroslawgajewski1
 
Machine Learning Benefits Across Industries
SynapseIndia
 
Ad

Callbacks and control flow in Node js

  • 1. ASYNCHRONOUS CODING IN NODEJS CALLBACKS AND CONTROL FLOW Thomas Roch, Formedix Ltd
  • 3. WHAT IS NODEJS Node.js uses an event-driven, non-blocking I/O model that makes it lightweight and efficient, perfect for data-intensive real-time applications that run across distributed devices. Event driven => event listeners Non-blocking IO => callbacks = ASYNCHRONOUS
  • 4. BEFORE WE START Non-blocking functions take callbacks (last argument) of two forms: function (err, res) { // Do something } function (res) { // Do something }
  • 5. WE ARE GOING TO TALK ABOUT Callback hell Inversion of control Control flow Promises Thunks Generators (or iterators)
  • 6. EXAMPLE A wish list server where one can: Create a whish list Add items to a whish list Retrieve the content of a whishlist Code available here
  • 7. REST API POST /whishList POST /whishList/{id} GET /whishList/{id}
  • 9. WHAT WE ARE GOING TO DO FIRST
  • 10. EXAMPLE A A mix of events and non-blocking functions with http.request() for: Creating a list Adding an item to a list Getting a list's content
  • 11. EXAMPLE B: Turn this mess into functions accepting callbacks With 3 functions: createList, addItem, getList... ...we are creating a nice "callback hell" aka "callback pyramid"
  • 12. ASYNC TO THE RESCUE First control flow example with https://github.com/caolan/async async.series() async.waterfall() async.parallel() Works with any non-blocking function "the node way"
  • 13. OK... WE'VE DONE STUFF IN PARALLEL Does this look good? What about avoiding iversion of control?
  • 14. EXAMPLE C: USING PROMISES ES6 feature but implementations available in ES5 Returns a deferred result (success or error) accessed using .then(): createList , addItem , getList Control flow using q : chaining promises, error propagation, Q.all... Compatible with Node API functions using Q.nfcall()
  • 15. BEFORE EXAMPLE D Generators (or iterators)! What are they? function* () { yield 1; return 2; }
  • 16. EXAMPLE D: USING GENERATORS What about yielding a promise or a thunk? a what? Control flow using co // The node way phoneMyPal(number, function (err, res) { console.log('hi'); }); // A thunk phoneMyPal(number)(function (err, res) { console.log('hi'); }); Let's thunkify createList, addItem, getList
  • 17. EXAMPLE D: USING GENERATORS works with thunks or promises co Compatible with Node API using thunkify Non-blocking code looking like it is not! Used by koa.js , a web application framework