SlideShare a Scribd company logo
1 of 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

More Related Content

What's hot

Asynchronous JavaScript Programming with Callbacks & Promises
Asynchronous JavaScript Programming with Callbacks & PromisesAsynchronous JavaScript Programming with Callbacks & Promises
Asynchronous JavaScript Programming with Callbacks & PromisesHùng Nguyễn Huy
 
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!
 
What Are Coroutines In Kotlin?
What Are Coroutines In Kotlin?What Are Coroutines In Kotlin?
What Are Coroutines In Kotlin?Simplilearn
 
An introduction to React.js
An introduction to React.jsAn introduction to React.js
An introduction to React.jsEmanuele DelBono
 
NodeJS - Server Side JS
NodeJS - Server Side JS NodeJS - Server Side JS
NodeJS - Server Side JS Ganesh Kondal
 
Nodejs functions & modules
Nodejs functions & modulesNodejs functions & modules
Nodejs functions & modulesmonikadeshmane
 
Introduction to Kotlin coroutines
Introduction to Kotlin coroutinesIntroduction to Kotlin coroutines
Introduction to Kotlin coroutinesRoman Elizarov
 
React JS - A quick introduction tutorial
React JS - A quick introduction tutorialReact JS - A quick introduction tutorial
React JS - A quick introduction tutorialMohammed Fazuluddin
 
NodeJS guide for beginners
NodeJS guide for beginnersNodeJS guide for beginners
NodeJS guide for beginnersEnoch Joshua
 
Tcp ip & io model
Tcp ip & io modelTcp ip & io model
Tcp ip & io modelNam Hyeonuk
 
Introduction to kotlin coroutines
Introduction to kotlin coroutinesIntroduction to kotlin coroutines
Introduction to kotlin coroutinesNAVER Engineering
 
Overview of React.JS - Internship Presentation - Week 5
Overview of React.JS - Internship Presentation - Week 5Overview of React.JS - Internship Presentation - Week 5
Overview of React.JS - Internship Presentation - Week 5Devang Garach
 

What's hot (20)

Asynchronous JavaScript Programming with Callbacks & Promises
Asynchronous JavaScript Programming with Callbacks & PromisesAsynchronous JavaScript Programming with Callbacks & Promises
Asynchronous JavaScript Programming with Callbacks & Promises
 
Callback Function
Callback FunctionCallback Function
Callback Function
 
Basics of JavaScript
Basics of JavaScriptBasics of JavaScript
Basics of JavaScript
 
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...
 
Express JS
Express JSExpress JS
Express JS
 
Javascript
JavascriptJavascript
Javascript
 
What Are Coroutines In Kotlin?
What Are Coroutines In Kotlin?What Are Coroutines In Kotlin?
What Are Coroutines In Kotlin?
 
Spring Boot
Spring BootSpring Boot
Spring Boot
 
An introduction to React.js
An introduction to React.jsAn introduction to React.js
An introduction to React.js
 
NodeJS - Server Side JS
NodeJS - Server Side JS NodeJS - Server Side JS
NodeJS - Server Side JS
 
Nodejs functions & modules
Nodejs functions & modulesNodejs functions & modules
Nodejs functions & modules
 
Introduction to Kotlin coroutines
Introduction to Kotlin coroutinesIntroduction to Kotlin coroutines
Introduction to Kotlin coroutines
 
React JS - A quick introduction tutorial
React JS - A quick introduction tutorialReact JS - A quick introduction tutorial
React JS - A quick introduction tutorial
 
Express js
Express jsExpress js
Express js
 
NodeJS guide for beginners
NodeJS guide for beginnersNodeJS guide for beginners
NodeJS guide for beginners
 
Tcp ip & io model
Tcp ip & io modelTcp ip & io model
Tcp ip & io model
 
Introduction to NodeJS
Introduction to NodeJSIntroduction to NodeJS
Introduction to NodeJS
 
Introduction to kotlin coroutines
Introduction to kotlin coroutinesIntroduction to kotlin coroutines
Introduction to kotlin coroutines
 
Express node js
Express node jsExpress node js
Express node js
 
Overview of React.JS - Internship Presentation - Week 5
Overview of React.JS - Internship Presentation - Week 5Overview of React.JS - Internship Presentation - Week 5
Overview of React.JS - Internship Presentation - Week 5
 

Viewers also liked

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
 

Viewers also liked (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
 

Similar to 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
 
Service Worker Presentation
Service Worker PresentationService Worker Presentation
Service Worker PresentationKyle Dorman
 

Similar to 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...
 
Service Worker Presentation
Service Worker PresentationService Worker Presentation
Service Worker Presentation
 

More from 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
 

More from 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
 

Recently uploaded

FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhisoniya singh
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
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
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Google AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGGoogle AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGSujit Pal
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersThousandEyes
 

Recently uploaded (20)

FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
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...
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Google AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGGoogle AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAG
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
 

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).)

Editor's Notes

  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.