SlideShare una empresa de Scribd logo
1 de 22
Descargar para leer sin conexión
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

Más contenido relacionado

La actualidad más candente

[Final] ReactJS presentation
[Final] ReactJS presentation[Final] ReactJS presentation
[Final] ReactJS presentation洪 鹏发
 
Introduction to Node js
Introduction to Node jsIntroduction to Node js
Introduction to Node jsAkshay Mathur
 
Angular & RXJS: examples and use cases
Angular & RXJS: examples and use casesAngular & RXJS: examples and use cases
Angular & RXJS: examples and use casesFabio Biondi
 
React.js - The Dawn of Virtual DOM
React.js - The Dawn of Virtual DOMReact.js - The Dawn of Virtual DOM
React.js - The Dawn of Virtual DOMJimit Shah
 
Introduction to RxJS
Introduction to RxJSIntroduction to RxJS
Introduction to RxJSBrainhub
 
Introduction to node.js
Introduction to node.jsIntroduction to node.js
Introduction to node.jsDinesh U
 
Introduction to Node JS.pdf
Introduction to Node JS.pdfIntroduction to Node JS.pdf
Introduction to Node JS.pdfBareen Shaikh
 
JavaScript - Chapter 11 - Events
 JavaScript - Chapter 11 - Events  JavaScript - Chapter 11 - Events
JavaScript - Chapter 11 - Events WebStackAcademy
 
Lets make a better react form
Lets make a better react formLets make a better react form
Lets make a better react formYao Nien Chung
 
Understanding react hooks
Understanding react hooksUnderstanding react hooks
Understanding react hooksMaulik Shah
 
What is component in reactjs
What is component in reactjsWhat is component in reactjs
What is component in reactjsmanojbkalla
 

La actualidad más candente (20)

[Final] ReactJS presentation
[Final] ReactJS presentation[Final] ReactJS presentation
[Final] ReactJS presentation
 
Introduction to Node js
Introduction to Node jsIntroduction to Node js
Introduction to Node js
 
Angular & RXJS: examples and use cases
Angular & RXJS: examples and use casesAngular & RXJS: examples and use cases
Angular & RXJS: examples and use cases
 
React/Redux
React/ReduxReact/Redux
React/Redux
 
React.js - The Dawn of Virtual DOM
React.js - The Dawn of Virtual DOMReact.js - The Dawn of Virtual DOM
React.js - The Dawn of Virtual DOM
 
Reactjs
Reactjs Reactjs
Reactjs
 
Introduction to RxJS
Introduction to RxJSIntroduction to RxJS
Introduction to RxJS
 
Introduction Node.js
Introduction Node.jsIntroduction Node.js
Introduction Node.js
 
Introduction to node.js
Introduction to node.jsIntroduction to node.js
Introduction to node.js
 
React workshop
React workshopReact workshop
React workshop
 
Nodejs presentation
Nodejs presentationNodejs presentation
Nodejs presentation
 
Introduction to Node JS.pdf
Introduction to Node JS.pdfIntroduction to Node JS.pdf
Introduction to Node JS.pdf
 
JavaScript - Chapter 11 - Events
 JavaScript - Chapter 11 - Events  JavaScript - Chapter 11 - Events
JavaScript - Chapter 11 - Events
 
JavaScript: Events Handling
JavaScript: Events HandlingJavaScript: Events Handling
JavaScript: Events Handling
 
Node js introduction
Node js introductionNode js introduction
Node js introduction
 
React hooks
React hooksReact hooks
React hooks
 
Lets make a better react form
Lets make a better react formLets make a better react form
Lets make a better react form
 
Understanding react hooks
Understanding react hooksUnderstanding react hooks
Understanding react hooks
 
What is component in reactjs
What is component in reactjsWhat is component in reactjs
What is component in reactjs
 
ReactJS presentation.pptx
ReactJS presentation.pptxReactJS presentation.pptx
ReactJS presentation.pptx
 

Destacado

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
 

Destacado (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 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
 
Service Worker Presentation
Service Worker PresentationService Worker Presentation
Service Worker PresentationKyle Dorman
 
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
 

Similar 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
 
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
 
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
 

Más 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
 

Más 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

IESVE Software for Florida Code Compliance Using ASHRAE 90.1-2019
IESVE Software for Florida Code Compliance Using ASHRAE 90.1-2019IESVE Software for Florida Code Compliance Using ASHRAE 90.1-2019
IESVE Software for Florida Code Compliance Using ASHRAE 90.1-2019IES VE
 
Bird eye's view on Camunda open source ecosystem
Bird eye's view on Camunda open source ecosystemBird eye's view on Camunda open source ecosystem
Bird eye's view on Camunda open source ecosystemAsko Soukka
 
IaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdf
IaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdfIaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdf
IaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdfDaniel Santiago Silva Capera
 
Igniting Next Level Productivity with AI-Infused Data Integration Workflows
Igniting Next Level Productivity with AI-Infused Data Integration WorkflowsIgniting Next Level Productivity with AI-Infused Data Integration Workflows
Igniting Next Level Productivity with AI-Infused Data Integration WorkflowsSafe Software
 
UiPath Studio Web workshop series - Day 6
UiPath Studio Web workshop series - Day 6UiPath Studio Web workshop series - Day 6
UiPath Studio Web workshop series - Day 6DianaGray10
 
COMPUTER 10 Lesson 8 - Building a Website
COMPUTER 10 Lesson 8 - Building a WebsiteCOMPUTER 10 Lesson 8 - Building a Website
COMPUTER 10 Lesson 8 - Building a Websitedgelyza
 
UiPath Studio Web workshop series - Day 7
UiPath Studio Web workshop series - Day 7UiPath Studio Web workshop series - Day 7
UiPath Studio Web workshop series - Day 7DianaGray10
 
Building AI-Driven Apps Using Semantic Kernel.pptx
Building AI-Driven Apps Using Semantic Kernel.pptxBuilding AI-Driven Apps Using Semantic Kernel.pptx
Building AI-Driven Apps Using Semantic Kernel.pptxUdaiappa Ramachandran
 
Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...
Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...
Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...DianaGray10
 
Nanopower In Semiconductor Industry.pdf
Nanopower  In Semiconductor Industry.pdfNanopower  In Semiconductor Industry.pdf
Nanopower In Semiconductor Industry.pdfPedro Manuel
 
Comparing Sidecar-less Service Mesh from Cilium and Istio
Comparing Sidecar-less Service Mesh from Cilium and IstioComparing Sidecar-less Service Mesh from Cilium and Istio
Comparing Sidecar-less Service Mesh from Cilium and IstioChristian Posta
 
Basic Building Blocks of Internet of Things.
Basic Building Blocks of Internet of Things.Basic Building Blocks of Internet of Things.
Basic Building Blocks of Internet of Things.YounusS2
 
UiPath Solutions Management Preview - Northern CA Chapter - March 22.pdf
UiPath Solutions Management Preview - Northern CA Chapter - March 22.pdfUiPath Solutions Management Preview - Northern CA Chapter - March 22.pdf
UiPath Solutions Management Preview - Northern CA Chapter - March 22.pdfDianaGray10
 
Meet the new FSP 3000 M-Flex800™
Meet the new FSP 3000 M-Flex800™Meet the new FSP 3000 M-Flex800™
Meet the new FSP 3000 M-Flex800™Adtran
 
Empowering Africa's Next Generation: The AI Leadership Blueprint
Empowering Africa's Next Generation: The AI Leadership BlueprintEmpowering Africa's Next Generation: The AI Leadership Blueprint
Empowering Africa's Next Generation: The AI Leadership BlueprintMahmoud Rabie
 
Artificial Intelligence & SEO Trends for 2024
Artificial Intelligence & SEO Trends for 2024Artificial Intelligence & SEO Trends for 2024
Artificial Intelligence & SEO Trends for 2024D Cloud Solutions
 
Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...
Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...
Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...Will Schroeder
 
20230202 - Introduction to tis-py
20230202 - Introduction to tis-py20230202 - Introduction to tis-py
20230202 - Introduction to tis-pyJamie (Taka) Wang
 
Linked Data in Production: Moving Beyond Ontologies
Linked Data in Production: Moving Beyond OntologiesLinked Data in Production: Moving Beyond Ontologies
Linked Data in Production: Moving Beyond OntologiesDavid Newbury
 

Último (20)

IESVE Software for Florida Code Compliance Using ASHRAE 90.1-2019
IESVE Software for Florida Code Compliance Using ASHRAE 90.1-2019IESVE Software for Florida Code Compliance Using ASHRAE 90.1-2019
IESVE Software for Florida Code Compliance Using ASHRAE 90.1-2019
 
Bird eye's view on Camunda open source ecosystem
Bird eye's view on Camunda open source ecosystemBird eye's view on Camunda open source ecosystem
Bird eye's view on Camunda open source ecosystem
 
IaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdf
IaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdfIaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdf
IaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdf
 
Igniting Next Level Productivity with AI-Infused Data Integration Workflows
Igniting Next Level Productivity with AI-Infused Data Integration WorkflowsIgniting Next Level Productivity with AI-Infused Data Integration Workflows
Igniting Next Level Productivity with AI-Infused Data Integration Workflows
 
UiPath Studio Web workshop series - Day 6
UiPath Studio Web workshop series - Day 6UiPath Studio Web workshop series - Day 6
UiPath Studio Web workshop series - Day 6
 
COMPUTER 10 Lesson 8 - Building a Website
COMPUTER 10 Lesson 8 - Building a WebsiteCOMPUTER 10 Lesson 8 - Building a Website
COMPUTER 10 Lesson 8 - Building a Website
 
UiPath Studio Web workshop series - Day 7
UiPath Studio Web workshop series - Day 7UiPath Studio Web workshop series - Day 7
UiPath Studio Web workshop series - Day 7
 
Building AI-Driven Apps Using Semantic Kernel.pptx
Building AI-Driven Apps Using Semantic Kernel.pptxBuilding AI-Driven Apps Using Semantic Kernel.pptx
Building AI-Driven Apps Using Semantic Kernel.pptx
 
201610817 - edge part1
201610817 - edge part1201610817 - edge part1
201610817 - edge part1
 
Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...
Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...
Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...
 
Nanopower In Semiconductor Industry.pdf
Nanopower  In Semiconductor Industry.pdfNanopower  In Semiconductor Industry.pdf
Nanopower In Semiconductor Industry.pdf
 
Comparing Sidecar-less Service Mesh from Cilium and Istio
Comparing Sidecar-less Service Mesh from Cilium and IstioComparing Sidecar-less Service Mesh from Cilium and Istio
Comparing Sidecar-less Service Mesh from Cilium and Istio
 
Basic Building Blocks of Internet of Things.
Basic Building Blocks of Internet of Things.Basic Building Blocks of Internet of Things.
Basic Building Blocks of Internet of Things.
 
UiPath Solutions Management Preview - Northern CA Chapter - March 22.pdf
UiPath Solutions Management Preview - Northern CA Chapter - March 22.pdfUiPath Solutions Management Preview - Northern CA Chapter - March 22.pdf
UiPath Solutions Management Preview - Northern CA Chapter - March 22.pdf
 
Meet the new FSP 3000 M-Flex800™
Meet the new FSP 3000 M-Flex800™Meet the new FSP 3000 M-Flex800™
Meet the new FSP 3000 M-Flex800™
 
Empowering Africa's Next Generation: The AI Leadership Blueprint
Empowering Africa's Next Generation: The AI Leadership BlueprintEmpowering Africa's Next Generation: The AI Leadership Blueprint
Empowering Africa's Next Generation: The AI Leadership Blueprint
 
Artificial Intelligence & SEO Trends for 2024
Artificial Intelligence & SEO Trends for 2024Artificial Intelligence & SEO Trends for 2024
Artificial Intelligence & SEO Trends for 2024
 
Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...
Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...
Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...
 
20230202 - Introduction to tis-py
20230202 - Introduction to tis-py20230202 - Introduction to tis-py
20230202 - Introduction to tis-py
 
Linked Data in Production: Moving Beyond Ontologies
Linked Data in Production: Moving Beyond OntologiesLinked Data in Production: Moving Beyond Ontologies
Linked Data in Production: Moving Beyond Ontologies
 

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