SlideShare uma empresa Scribd logo
1 de 22
Avoiding Callback Hell using
Promises in Node.js
Node.js is event-based..
In a normal process cycle the webserver while
processing the request will have to wait for the IO
operations and thus blocking the next request to be
processed.
Node.JS process each request as events, The server
doesn’t wait for the IO operation to complete while
it can handle other request at the same time.
When the IO operation of first request is completed
it will call-back the server to complete the request.
Threads VS Event-driven / Non-Blocking? Blocking?
• By introducing callbacks. Node can
move on to other requests and
whenever the callback is called, node
will process is..
•Non-blocking code is to be read as «
put function and params in queue and
fire callback when you reach the end of
the queue »
• Blocking= return,
Non-Blocking= no return. Only
callbacks
Callback Example
fs = require('fs');
fs.readFile('f1.txt','utf8',function(err,data){
if (err) {
return console.log(err);
}
console.log(data);
});
Callback Hell - Pyramid of Doom
func1(param, function(err, res) {
func2(param, function(err, res) {
func3(param, function(err, res) {
func4(param, function(err, res) {
func5(param, function(err, res) {
func6(param, function(err, res) {
func7(param, function(err, res) {
func8(param, function(err, res) {
func9(param, function(err, res) {
// Do something…
});
});
});
});
});
});
});
});
});
Best case, this is linear
func1
func2
func3
. . .
func9
But it can branch
func1
func2
func3
. . .
func9
func2
func3func3 func3
. . .
func9
. . .
func9
. . .
func9
Separate Callback
fs = require('fs');
callback = function(err,data){
if (err) {
return console.log(err);
}
console.log(data);
}
fs.readFile('f1.txt','utf8',callback);
Can turn this:
var db = require('somedatabaseprovider');
http.get('/recentposts', function(req, res){
db.openConnection('host', creds, function(err,
conn){
res.param['posts'].forEach(post) {
conn.query('select * from users where id=' +
post['user'],function(err,results){
conn.close();
res.send(results[0]);
});
}
});
});
…into this
var db = require('somedatabaseprovider');
http.get('/recentposts', afterRecentPosts);
function afterRecentPosts(req, res) {
db.openConnection('host', creds, function(err, conn) {
afterDBConnected(res, conn);
});
}
function afterDBConnected(err, conn) {
res.param['posts'].forEach(post) {
conn.query('select * from users where id='+post['user'],afterQuery);
}
}
function afterQuery(err, results) {
conn.close();
res.send(results[0]);
}
Good start!
 Callback function separation is a nice
aesthetic fix
 The code is more readable, and thus
more maintainable
 But it doesn’t improve your control
flow
Promises - Description
 Promises take a call to an asynchronous
function and wrap it with an object whose
methods proxy when the wrapped
function either completes or errors
 A good Promise library also provides a
set of control methods on that object
wrapper to handle composition of
multiple Promise-ified asynchronous
method calls
 Promises use the best qualities of an
object--encapsulation of state--to track
the state of an asynchronous call
Again, Why Promises?
 It’s a spec:
http://wiki.commonjs.org/wiki/Promises/A
 Generally supported by a bunch of libs
both browser and server-side:
◦ jQuery (sort of, supposedly doesn’t fully work
like Promises/A)
◦ AngularJS
◦ Q library (https://github.com/kriskowal/q)
 Provides separation of concerns
between wrapping and flow of control
handling of deferred activities
Pyramid of Doom Again
 step1(function (value1) {
step2(value1, function(value2){
step3(value2,
function(value3){
step4(value3,
function(value4){
// Do something with value4
});
});
});
});
 step1 // a Promise obj
.then(step2)
.then(step3)
.then(step4)
.then(function (value4)
//Do something with value 4
})
.fail( function (error) {
◦ Handle any error from step
through step4
})
Chaining
 return getUsername()
.then(function (username) {
return getUser(username)
.then(function (user) {
// if we get here without an error,
// the value returned here
// or the exception thrown here
// resolves the promise returned
// by the first line
})
});
 return getUsername()
.then(function (username) {
return
getUser(username);
})
.then(function (user) {
// if we get here without an
error,
// the value returned here
// or the exception thrown here
// resolves the promise returned
// by the first line
});
Nesting
 It’s useful to nest handlers if you need to capture multiple input
values in your closure.
 function authenticate()
{
return getUsername()
.then(function (username) {
return getUser(username);
})
// chained because we will not need the user name in the next event
.then(function (user) {
return getPassword() // nested because we need both user and password next
.then(function (password) {
if (user.passwordHash !== hash(password)) {
throw new Error("Can't authenticate");
}
});
});
}
Combination
 return Q.all([
eventualAdd(2, 2),
eventualAdd(10, 20)
])
.then ( function getAll(…args){
var firstResult = args[0][0];
// and so on….
});
 function eventualAdd(a, b) {
return Q.spread([a, b], function (a, b) {
return a + b;
})
}
Using Combination and
spread
 Using both we can avoid chaining:
◦ return getUsername()
.then(function (username) {
return [username, getUser(username)];
})
.spread(function (username, user) {
});
Creating Promises - Using
Deferreds
 var deferred = Q.defer();
FS.readFile("foo.txt", "utf-8", function (error, text) {
if (error) {
deferred.reject(new Error(error));
} else {
deferred.resolve(text);
}
});
return deferred.promise;
 deferred.reject(new Error(error)); // is shorthand for:
var rejection = Q.fcall(function (error) {
throw new Error(error);
});
deferred.resolve(rejection);
Some Important Methods of Q
Library
 promise.finally(callback)
◦ useful for collecting resources regardless of whether
a job succeeded, like closing a database connection,
shutting a server down, or deleting an unneeded key
from an object.
 promise.done(onFulfilled, onRejected,
onProgress)
◦ This method should be used to terminate chains of
promises that will not be passed elsewhere. Since
exceptions thrown in then callbacks are consumed
and transformed into rejections, exceptions at the end
of the chain are easy to accidentally, silently ignore.
◦ The Golden Rule of done vs. then usage is: either
return your promise to someone else, or if the chain
ends with you, call done to terminate it. Terminating
with catch is not sufficient because the catch handler
may itself throw an error.
Some more…
 promise.delay(ms)
◦ If the static version of Q.delay is passed
only a single argument, it returns a
promise that will be fulfilled with undefined
after at least ms milliseconds have
passed. (If it's called with two arguments,
it uses the usual static-counterpart
translation, i.e. Q.delay(value, ms) is
equivalent to Q(value).delay(ms).)
Thank You

Mais conteúdo relacionado

Mais procurados

ES2015 / ES6: Basics of modern Javascript
ES2015 / ES6: Basics of modern JavascriptES2015 / ES6: Basics of modern Javascript
ES2015 / ES6: Basics of modern JavascriptWojciech Dzikowski
 
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
 
Service Worker Presentation
Service Worker PresentationService Worker Presentation
Service Worker PresentationKyle Dorman
 
Basic JavaScript Tutorial
Basic JavaScript TutorialBasic JavaScript Tutorial
Basic JavaScript TutorialDHTMLExtreme
 
Token Authentication in ASP.NET Core
Token Authentication in ASP.NET CoreToken Authentication in ASP.NET Core
Token Authentication in ASP.NET CoreStormpath
 
Asynchronous JavaScript Programming
Asynchronous JavaScript ProgrammingAsynchronous JavaScript Programming
Asynchronous JavaScript ProgrammingHaim Michael
 
Java script final presentation
Java script final presentationJava script final presentation
Java script final presentationAdhoura Academy
 
Introduction to Actor Model and Akka
Introduction to Actor Model and AkkaIntroduction to Actor Model and Akka
Introduction to Actor Model and AkkaYung-Lin Ho
 
JavaScript - Chapter 7 - Advanced Functions
 JavaScript - Chapter 7 - Advanced Functions JavaScript - Chapter 7 - Advanced Functions
JavaScript - Chapter 7 - Advanced FunctionsWebStackAcademy
 
React event
React eventReact event
React eventDucat
 
Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...
Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...
Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...Edureka!
 
A Deeper look into Javascript Basics
A Deeper look into Javascript BasicsA Deeper look into Javascript Basics
A Deeper look into Javascript BasicsMindfire Solutions
 
Introduction to ASP.NET Core
Introduction to ASP.NET CoreIntroduction to ASP.NET Core
Introduction to ASP.NET CoreAvanade Nederland
 

Mais procurados (20)

JavaScript Promises
JavaScript PromisesJavaScript Promises
JavaScript Promises
 
ES2015 / ES6: Basics of modern Javascript
ES2015 / ES6: Basics of modern JavascriptES2015 / ES6: Basics of modern Javascript
ES2015 / ES6: Basics of modern Javascript
 
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...
 
Service Worker Presentation
Service Worker PresentationService Worker Presentation
Service Worker Presentation
 
Basic JavaScript Tutorial
Basic JavaScript TutorialBasic JavaScript Tutorial
Basic JavaScript Tutorial
 
webworkers
webworkerswebworkers
webworkers
 
Token Authentication in ASP.NET Core
Token Authentication in ASP.NET CoreToken Authentication in ASP.NET Core
Token Authentication in ASP.NET Core
 
Express JS
Express JSExpress JS
Express JS
 
Asynchronous JavaScript Programming
Asynchronous JavaScript ProgrammingAsynchronous JavaScript Programming
Asynchronous JavaScript Programming
 
Java script final presentation
Java script final presentationJava script final presentation
Java script final presentation
 
Introduction to Actor Model and Akka
Introduction to Actor Model and AkkaIntroduction to Actor Model and Akka
Introduction to Actor Model and Akka
 
API
APIAPI
API
 
JavaScript - Chapter 7 - Advanced Functions
 JavaScript - Chapter 7 - Advanced Functions JavaScript - Chapter 7 - Advanced Functions
JavaScript - Chapter 7 - Advanced Functions
 
React event
React eventReact event
React event
 
Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...
Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...
Node.js Tutorial for Beginners | Node.js Web Application Tutorial | Node.js T...
 
A Deeper look into Javascript Basics
A Deeper look into Javascript BasicsA Deeper look into Javascript Basics
A Deeper look into Javascript Basics
 
Express js
Express jsExpress js
Express js
 
Nodejs presentation
Nodejs presentationNodejs presentation
Nodejs presentation
 
Rest API
Rest APIRest API
Rest API
 
Introduction to ASP.NET Core
Introduction to ASP.NET CoreIntroduction to ASP.NET Core
Introduction to ASP.NET Core
 

Destaque

Avoiding Callback Hell with Async.js
Avoiding Callback Hell with Async.jsAvoiding Callback Hell with Async.js
Avoiding Callback Hell with Async.jscacois
 
Callbacks, promises, generators - asynchronous javascript
Callbacks, promises, generators - asynchronous javascriptCallbacks, promises, generators - asynchronous javascript
Callbacks, promises, generators - asynchronous javascriptŁukasz Kużyński
 
Beyond the Callback: Yield Control with Javascript Generators
Beyond the Callback: Yield Control with Javascript GeneratorsBeyond the Callback: Yield Control with Javascript Generators
Beyond the Callback: Yield Control with Javascript GeneratorsDarren Cruse
 
Using Node.js to improve the performance of Mobile apps and Mobile web
Using Node.js to improve  the performance of  Mobile apps and Mobile webUsing Node.js to improve  the performance of  Mobile apps and Mobile web
Using Node.js to improve the performance of Mobile apps and Mobile webTom Croucher
 
Beautiful code instead of callback hell using ES6 Generators, Koa, Bluebird (...
Beautiful code instead of callback hell using ES6 Generators, Koa, Bluebird (...Beautiful code instead of callback hell using ES6 Generators, Koa, Bluebird (...
Beautiful code instead of callback hell using ES6 Generators, Koa, Bluebird (...andreaslubbe
 
From Callback Hell to Async Heaven - Promises!
From Callback Hell to Async Heaven - Promises!From Callback Hell to Async Heaven - Promises!
From Callback Hell to Async Heaven - Promises!Gil Tayar
 
Sync with async
Sync with  asyncSync with  async
Sync with asyncprabathsl
 
Promises And Chaining In AngularJS - Into Callback Hell And Back Again
Promises And Chaining In AngularJS - Into Callback Hell And Back AgainPromises And Chaining In AngularJS - Into Callback Hell And Back Again
Promises And Chaining In AngularJS - Into Callback Hell And Back AgainHans-Gunther Schmidt
 
Indian healthcare industry presentation
Indian healthcare industry presentationIndian healthcare industry presentation
Indian healthcare industry presentationswatilembhe
 
Indian Healthcare System An Overiew
Indian Healthcare System An OveriewIndian Healthcare System An Overiew
Indian Healthcare System An Overiewdrdivyahm
 
Healthcare industry ppt
Healthcare industry pptHealthcare industry ppt
Healthcare industry pptAnkit Agarwal
 

Destaque (11)

Avoiding Callback Hell with Async.js
Avoiding Callback Hell with Async.jsAvoiding Callback Hell with Async.js
Avoiding Callback Hell with Async.js
 
Callbacks, promises, generators - asynchronous javascript
Callbacks, promises, generators - asynchronous javascriptCallbacks, promises, generators - asynchronous javascript
Callbacks, promises, generators - asynchronous javascript
 
Beyond the Callback: Yield Control with Javascript Generators
Beyond the Callback: Yield Control with Javascript GeneratorsBeyond the Callback: Yield Control with Javascript Generators
Beyond the Callback: Yield Control with Javascript Generators
 
Using Node.js to improve the performance of Mobile apps and Mobile web
Using Node.js to improve  the performance of  Mobile apps and Mobile webUsing Node.js to improve  the performance of  Mobile apps and Mobile web
Using Node.js to improve the performance of Mobile apps and Mobile web
 
Beautiful code instead of callback hell using ES6 Generators, Koa, Bluebird (...
Beautiful code instead of callback hell using ES6 Generators, Koa, Bluebird (...Beautiful code instead of callback hell using ES6 Generators, Koa, Bluebird (...
Beautiful code instead of callback hell using ES6 Generators, Koa, Bluebird (...
 
From Callback Hell to Async Heaven - Promises!
From Callback Hell to Async Heaven - Promises!From Callback Hell to Async Heaven - Promises!
From Callback Hell to Async Heaven - Promises!
 
Sync with async
Sync with  asyncSync with  async
Sync with async
 
Promises And Chaining In AngularJS - Into Callback Hell And Back Again
Promises And Chaining In AngularJS - Into Callback Hell And Back AgainPromises And Chaining In AngularJS - Into Callback Hell And Back Again
Promises And Chaining In AngularJS - Into Callback Hell And Back Again
 
Indian healthcare industry presentation
Indian healthcare industry presentationIndian healthcare industry presentation
Indian healthcare industry presentation
 
Indian Healthcare System An Overiew
Indian Healthcare System An OveriewIndian Healthcare System An Overiew
Indian Healthcare System An Overiew
 
Healthcare industry ppt
Healthcare industry pptHealthcare industry ppt
Healthcare industry ppt
 

Semelhante a Avoiding callback hell in Node js using promises

Asynchronous development in JavaScript
Asynchronous development  in JavaScriptAsynchronous development  in JavaScript
Asynchronous development in JavaScriptAmitai Barnea
 
"Service Worker: Let Your Web App Feel Like a Native "
"Service Worker: Let Your Web App Feel Like a Native ""Service Worker: Let Your Web App Feel Like a Native "
"Service Worker: Let Your Web App Feel Like a Native "FDConf
 
The Promised Land (in Angular)
The Promised Land (in Angular)The Promised Land (in Angular)
The Promised Land (in Angular)Domenic Denicola
 
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 changerSandro Paganotti
 
How and why i roll my own node.js framework
How and why i roll my own node.js frameworkHow and why i roll my own node.js framework
How and why i roll my own node.js frameworkBen Lin
 
Promises look into the async future
Promises look into the async futurePromises look into the async future
Promises look into the async futureslicejs
 
An opinionated intro to Node.js - devrupt hospitality hackathon
An opinionated intro to Node.js - devrupt hospitality hackathonAn opinionated intro to Node.js - devrupt hospitality hackathon
An opinionated intro to Node.js - devrupt hospitality hackathonLuciano Mammino
 
Building Scalable Stateless Applications with RxJava
Building Scalable Stateless Applications with RxJavaBuilding Scalable Stateless Applications with RxJava
Building Scalable Stateless Applications with RxJavaRick Warren
 
Promises - Asynchronous Control Flow
Promises - Asynchronous Control FlowPromises - Asynchronous Control Flow
Promises - Asynchronous Control FlowHenrique Barcelos
 
JSON Part 3: Asynchronous Ajax & JQuery Deferred
JSON Part 3: Asynchronous Ajax & JQuery DeferredJSON Part 3: Asynchronous Ajax & JQuery Deferred
JSON Part 3: Asynchronous Ajax & JQuery DeferredJeff Fox
 
Douglas Crockford: Serversideness
Douglas Crockford: ServersidenessDouglas Crockford: Serversideness
Douglas Crockford: ServersidenessWebExpo
 
Fundamental Node.js (Workshop bersama Front-end Developer GITS Indonesia, War...
Fundamental Node.js (Workshop bersama Front-end Developer GITS Indonesia, War...Fundamental Node.js (Workshop bersama Front-end Developer GITS Indonesia, War...
Fundamental Node.js (Workshop bersama Front-end Developer GITS Indonesia, War...GITS Indonesia
 
Javascript Promises/Q Library
Javascript Promises/Q LibraryJavascript Promises/Q Library
Javascript Promises/Q Libraryasync_io
 
JavaScript Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing UpDavid Padbury
 
JavaScript Interview Questions 2023
JavaScript Interview Questions 2023JavaScript Interview Questions 2023
JavaScript Interview Questions 2023Laurence Svekis ✔
 
Building serverless application on the Apache Openwhisk platform
Building serverless application on the Apache Openwhisk platformBuilding serverless application on the Apache Openwhisk platform
Building serverless application on the Apache Openwhisk platformLucio Grenzi
 
Lucio Grenzi - Building serverless applications on the Apache OpenWhisk platf...
Lucio Grenzi - Building serverless applications on the Apache OpenWhisk platf...Lucio Grenzi - Building serverless applications on the Apache OpenWhisk platf...
Lucio Grenzi - Building serverless applications on the Apache OpenWhisk platf...Codemotion
 
Bonnes pratiques de développement avec Node js
Bonnes pratiques de développement avec Node jsBonnes pratiques de développement avec Node js
Bonnes pratiques de développement avec Node jsFrancois Zaninotto
 

Semelhante a Avoiding callback hell in Node js using promises (20)

Asynchronous development in JavaScript
Asynchronous development  in JavaScriptAsynchronous development  in JavaScript
Asynchronous development in JavaScript
 
"Service Worker: Let Your Web App Feel Like a Native "
"Service Worker: Let Your Web App Feel Like a Native ""Service Worker: Let Your Web App Feel Like a Native "
"Service Worker: Let Your Web App Feel Like a Native "
 
Server Side Swift: Vapor
Server Side Swift: VaporServer Side Swift: Vapor
Server Side Swift: Vapor
 
The Promised Land (in Angular)
The Promised Land (in Angular)The Promised Land (in Angular)
The Promised Land (in Angular)
 
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
 
How and why i roll my own node.js framework
How and why i roll my own node.js frameworkHow and why i roll my own node.js framework
How and why i roll my own node.js framework
 
Promises look into the async future
Promises look into the async futurePromises look into the async future
Promises look into the async future
 
An opinionated intro to Node.js - devrupt hospitality hackathon
An opinionated intro to Node.js - devrupt hospitality hackathonAn opinionated intro to Node.js - devrupt hospitality hackathon
An opinionated intro to Node.js - devrupt hospitality hackathon
 
Building Scalable Stateless Applications with RxJava
Building Scalable Stateless Applications with RxJavaBuilding Scalable Stateless Applications with RxJava
Building Scalable Stateless Applications with RxJava
 
Promises - Asynchronous Control Flow
Promises - Asynchronous Control FlowPromises - Asynchronous Control Flow
Promises - Asynchronous Control Flow
 
JSON Part 3: Asynchronous Ajax & JQuery Deferred
JSON Part 3: Asynchronous Ajax & JQuery DeferredJSON Part 3: Asynchronous Ajax & JQuery Deferred
JSON Part 3: Asynchronous Ajax & JQuery Deferred
 
JavaScript Promises
JavaScript PromisesJavaScript Promises
JavaScript Promises
 
Douglas Crockford: Serversideness
Douglas Crockford: ServersidenessDouglas Crockford: Serversideness
Douglas Crockford: Serversideness
 
Fundamental Node.js (Workshop bersama Front-end Developer GITS Indonesia, War...
Fundamental Node.js (Workshop bersama Front-end Developer GITS Indonesia, War...Fundamental Node.js (Workshop bersama Front-end Developer GITS Indonesia, War...
Fundamental Node.js (Workshop bersama Front-end Developer GITS Indonesia, War...
 
Javascript Promises/Q Library
Javascript Promises/Q LibraryJavascript Promises/Q Library
Javascript Promises/Q Library
 
JavaScript Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing Up
 
JavaScript Interview Questions 2023
JavaScript Interview Questions 2023JavaScript Interview Questions 2023
JavaScript Interview Questions 2023
 
Building serverless application on the Apache Openwhisk platform
Building serverless application on the Apache Openwhisk platformBuilding serverless application on the Apache Openwhisk platform
Building serverless application on the Apache Openwhisk platform
 
Lucio Grenzi - Building serverless applications on the Apache OpenWhisk platf...
Lucio Grenzi - Building serverless applications on the Apache OpenWhisk platf...Lucio Grenzi - Building serverless applications on the Apache OpenWhisk platf...
Lucio Grenzi - Building serverless applications on the Apache OpenWhisk platf...
 
Bonnes pratiques de développement avec Node js
Bonnes pratiques de développement avec Node jsBonnes pratiques de développement avec Node js
Bonnes pratiques de développement avec Node js
 

Mais de Ankit Agarwal

Product Innovation: An Effective Strategy To Penetrate Into Small Towns And ...
Product Innovation: An Effective Strategy To  Penetrate Into Small Towns And ...Product Innovation: An Effective Strategy To  Penetrate Into Small Towns And ...
Product Innovation: An Effective Strategy To Penetrate Into Small Towns And ...Ankit Agarwal
 
Private label report
Private label reportPrivate label report
Private label reportAnkit Agarwal
 
14 financial administration
14   financial administration14   financial administration
14 financial administrationAnkit Agarwal
 
10 personnel administration
10   personnel administration10   personnel administration
10 personnel administrationAnkit Agarwal
 
Food Processing Industry of India
Food Processing Industry of IndiaFood Processing Industry of India
Food Processing Industry of IndiaAnkit Agarwal
 
Marketing final version
Marketing final versionMarketing final version
Marketing final versionAnkit Agarwal
 
Food Processing Industry India
Food Processing Industry IndiaFood Processing Industry India
Food Processing Industry IndiaAnkit Agarwal
 

Mais de Ankit Agarwal (16)

Product Innovation: An Effective Strategy To Penetrate Into Small Towns And ...
Product Innovation: An Effective Strategy To  Penetrate Into Small Towns And ...Product Innovation: An Effective Strategy To  Penetrate Into Small Towns And ...
Product Innovation: An Effective Strategy To Penetrate Into Small Towns And ...
 
Private label report
Private label reportPrivate label report
Private label report
 
Amul
AmulAmul
Amul
 
Fdi in retail
Fdi in retailFdi in retail
Fdi in retail
 
Sabtv
SabtvSabtv
Sabtv
 
14 financial administration
14   financial administration14   financial administration
14 financial administration
 
Bicyle industry
Bicyle industryBicyle industry
Bicyle industry
 
10 personnel administration
10   personnel administration10   personnel administration
10 personnel administration
 
5 public order
5   public order5   public order
5 public order
 
Security (finance)
Security (finance)Security (finance)
Security (finance)
 
Marico IT structure
Marico IT structureMarico IT structure
Marico IT structure
 
Marico IT structure
Marico IT structureMarico IT structure
Marico IT structure
 
Food Processing Industry of India
Food Processing Industry of IndiaFood Processing Industry of India
Food Processing Industry of India
 
Marketing final version
Marketing final versionMarketing final version
Marketing final version
 
Food Processing Industry India
Food Processing Industry IndiaFood Processing Industry India
Food Processing Industry India
 
Korea
KoreaKorea
Korea
 

Último

Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodJuan lago vázquez
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu SubbuApidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbuapidays
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CVKhem
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...Zilliz
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...apidays
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAndrey Devyatkin
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyKhushali Kathiriya
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWERMadyBayot
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Zilliz
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Jeffrey Haguewood
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...apidays
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...apidays
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDropbox
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdflior mazor
 

Último (20)

Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu SubbuApidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 

Avoiding callback hell in Node js using promises

  • 1. Avoiding Callback Hell using Promises in Node.js
  • 2. Node.js is event-based.. In a normal process cycle the webserver while processing the request will have to wait for the IO operations and thus blocking the next request to be processed. Node.JS process each request as events, The server doesn’t wait for the IO operation to complete while it can handle other request at the same time. When the IO operation of first request is completed it will call-back the server to complete the request.
  • 3. Threads VS Event-driven / Non-Blocking? Blocking? • By introducing callbacks. Node can move on to other requests and whenever the callback is called, node will process is.. •Non-blocking code is to be read as « put function and params in queue and fire callback when you reach the end of the queue » • Blocking= return, Non-Blocking= no return. Only callbacks
  • 4. Callback Example fs = require('fs'); fs.readFile('f1.txt','utf8',function(err,data){ if (err) { return console.log(err); } console.log(data); });
  • 5. Callback Hell - Pyramid of Doom func1(param, function(err, res) { func2(param, function(err, res) { func3(param, function(err, res) { func4(param, function(err, res) { func5(param, function(err, res) { func6(param, function(err, res) { func7(param, function(err, res) { func8(param, function(err, res) { func9(param, function(err, res) { // Do something… }); }); }); }); }); }); }); }); });
  • 6. Best case, this is linear func1 func2 func3 . . . func9
  • 7. But it can branch func1 func2 func3 . . . func9 func2 func3func3 func3 . . . func9 . . . func9 . . . func9
  • 8. Separate Callback fs = require('fs'); callback = function(err,data){ if (err) { return console.log(err); } console.log(data); } fs.readFile('f1.txt','utf8',callback);
  • 9. Can turn this: var db = require('somedatabaseprovider'); http.get('/recentposts', function(req, res){ db.openConnection('host', creds, function(err, conn){ res.param['posts'].forEach(post) { conn.query('select * from users where id=' + post['user'],function(err,results){ conn.close(); res.send(results[0]); }); } }); });
  • 10. …into this var db = require('somedatabaseprovider'); http.get('/recentposts', afterRecentPosts); function afterRecentPosts(req, res) { db.openConnection('host', creds, function(err, conn) { afterDBConnected(res, conn); }); } function afterDBConnected(err, conn) { res.param['posts'].forEach(post) { conn.query('select * from users where id='+post['user'],afterQuery); } } function afterQuery(err, results) { conn.close(); res.send(results[0]); }
  • 11. Good start!  Callback function separation is a nice aesthetic fix  The code is more readable, and thus more maintainable  But it doesn’t improve your control flow
  • 12. Promises - Description  Promises take a call to an asynchronous function and wrap it with an object whose methods proxy when the wrapped function either completes or errors  A good Promise library also provides a set of control methods on that object wrapper to handle composition of multiple Promise-ified asynchronous method calls  Promises use the best qualities of an object--encapsulation of state--to track the state of an asynchronous call
  • 13. Again, Why Promises?  It’s a spec: http://wiki.commonjs.org/wiki/Promises/A  Generally supported by a bunch of libs both browser and server-side: ◦ jQuery (sort of, supposedly doesn’t fully work like Promises/A) ◦ AngularJS ◦ Q library (https://github.com/kriskowal/q)  Provides separation of concerns between wrapping and flow of control handling of deferred activities
  • 14. Pyramid of Doom Again  step1(function (value1) { step2(value1, function(value2){ step3(value2, function(value3){ step4(value3, function(value4){ // Do something with value4 }); }); }); });  step1 // a Promise obj .then(step2) .then(step3) .then(step4) .then(function (value4) //Do something with value 4 }) .fail( function (error) { ◦ Handle any error from step through step4 })
  • 15. Chaining  return getUsername() .then(function (username) { return getUser(username) .then(function (user) { // if we get here without an error, // the value returned here // or the exception thrown here // resolves the promise returned // by the first line }) });  return getUsername() .then(function (username) { return getUser(username); }) .then(function (user) { // if we get here without an error, // the value returned here // or the exception thrown here // resolves the promise returned // by the first line });
  • 16. Nesting  It’s useful to nest handlers if you need to capture multiple input values in your closure.  function authenticate() { return getUsername() .then(function (username) { return getUser(username); }) // chained because we will not need the user name in the next event .then(function (user) { return getPassword() // nested because we need both user and password next .then(function (password) { if (user.passwordHash !== hash(password)) { throw new Error("Can't authenticate"); } }); }); }
  • 17. Combination  return Q.all([ eventualAdd(2, 2), eventualAdd(10, 20) ]) .then ( function getAll(…args){ var firstResult = args[0][0]; // and so on…. });  function eventualAdd(a, b) { return Q.spread([a, b], function (a, b) { return a + b; }) }
  • 18. Using Combination and spread  Using both we can avoid chaining: ◦ return getUsername() .then(function (username) { return [username, getUser(username)]; }) .spread(function (username, user) { });
  • 19. Creating Promises - Using Deferreds  var deferred = Q.defer(); FS.readFile("foo.txt", "utf-8", function (error, text) { if (error) { deferred.reject(new Error(error)); } else { deferred.resolve(text); } }); return deferred.promise;  deferred.reject(new Error(error)); // is shorthand for: var rejection = Q.fcall(function (error) { throw new Error(error); }); deferred.resolve(rejection);
  • 20. Some Important Methods of Q Library  promise.finally(callback) ◦ useful for collecting resources regardless of whether a job succeeded, like closing a database connection, shutting a server down, or deleting an unneeded key from an object.  promise.done(onFulfilled, onRejected, onProgress) ◦ This method should be used to terminate chains of promises that will not be passed elsewhere. Since exceptions thrown in then callbacks are consumed and transformed into rejections, exceptions at the end of the chain are easy to accidentally, silently ignore. ◦ The Golden Rule of done vs. then usage is: either return your promise to someone else, or if the chain ends with you, call done to terminate it. Terminating with catch is not sufficient because the catch handler may itself throw an error.
  • 21. Some more…  promise.delay(ms) ◦ If the static version of Q.delay is passed only a single argument, it returns a promise that will be fulfilled with undefined after at least ms milliseconds have passed. (If it's called with two arguments, it uses the usual static-counterpart translation, i.e. Q.delay(value, ms) is equivalent to Q(value).delay(ms).)

Notas do Editor

  1. So let’s remove the inline callback…
  2. And has a devil.
  3. Now let’s visualize what’s going on here. When a function is called, it goes off into the asynchronous, background ether. And the rest of the file continues to execute. When the function finishes its asynchronous task, it calls the callback. This ends up looking something like this, except the functions aren’t calling each other directly. Regardless, in the best case scenario, we have a linear callback path. Function 1 finishes, calls function 2. function 2 finishes, calls function 3. etc. Now without the asynchronous component, we’d be all set. These functions would call each other in a cascading fashion. But alas, these callbacks are asynchronous.
  4. Which means they can _branch_
  5. … and define it as an object. We can then pass it into the async method. This is much easier to read, which is good.
  6. Sure, a few more lines of code. But look how much better the organization is. Look how much easier it would be to come in and immediately understand this code.