SlideShare a Scribd company logo
1 of 19
Download to read offline
Unfulfilled
(Newborn)
Promise
Fulfilled
(Resolved)
Promise
Failed
(Rejected)
PromisePromises Crash Course
Nicholas van de Walle
13
A resolved promise is essentially a “value”
A rejected promise is essentially a caught ErrorA rejected promise is essentially a caught Error
(error only catches OperationalErrors)
These errors jump straight to the next “catch” or “error”
.catch(fn ( ) {
// handlin’
})
.catch(fn ( ) {
// handlin’
});
.then(fn ( ) {
// executin’
})
.then(fn ( ) {
// executin’
})
getUserAsync({
userID: ‘abc’
})
fn(err) {
// handlin’
}
fn(err) {
// handlin’
}
fn(err) {
// handlin’
}
Promises allow you to create asynchronous
“Pipelines”
Sending JSON
fn(err) {
// handlin’
}
Error Handler
(Generic)
Diff’rent
404’d
Puppies Got! … then
Get all the user’s puppies
404’d User Got! … then
Get me the user
Creating Promises
(A Contrived Example)
fn x2Later ( num, callback ) {
process.nextTick( fn () {
callback( num * 2 )
})
}
fn x2Async ( num ) {
return new Promise( fn ( resolver, rejector ) {
x2Later( num, resolver )
})
}
Use Promisify
(A Contrived Example)
fn x2Later ( num, callback ) {
process.nextTick( fn () {
callback( num * 2 )
})
}
x2Async = Promise.promisify( x2Later )
Just use promisifyAll
( Always do this at the root require )
var fs = Promise.promisifyAll(require(‘fs’))
fs.readFileAsync(file)fs.readFile(file, cb)
fs.openAsync(file)fs.open(file, cb)
fs.renameAsync(old, new)fs.rename(old, new, cb)
fs.mkdirAsync(path)fs.mkdir(path, cb)
Wrapping non-compliant API’s is easy
var getUsersAsync = fn ( userIds ) {
return new Promise( fn ( resolve, reject ) {
// Noncompliant API uses an object of callbacks
getUsers( userIds, {
success : fn ( err, data ) {
(err) ? reject(err) : resolve(data.users)
},
error : fn ( status, obj ) {
// TODO (Nicholas): REFACTOR TO BE JSON API COMPLIANT
reject( new Promise.OperationalError( status.description ) )
}
})
})
}
Sometimes you need to wait for two (or more)
operations to succeeed
Sending JSON
Do some logic
Join’d promises
promise
Users Got! … spread
Join these two GetUser promises
You can easily manage collections of promises
( Also: settle, any, some, props )
all
At least
one failed
All Successful
And your functional buddies are here too!
( Also: reduce, each, filter )
map
At least
one failed
All Successful
Testing Promises is Easy (With Chai as Promised)
( Thanks to Domenic Denicola, now of Google Chrome team )
.should.eventually.equal( )
.should.eventually.equal( )
.should.be.rejectedWith( )
.should.be.rejectedWith( )
Advanced Concepts
Timers
Statefulness &
Context
Resource
Management
Inspection
Timers let you control when and if a promise fulfills
Timeout
Delay
… is the opposite of ...
Bluebird gives you many helpful inspection methods
reflect
isFulfilled
isRejected
isPending
value
reason
?
?
??
???
???
Err
Reflect is a super powerful generic Settle
Promise.props({
"First" : doThingAsync().reflect(),
"Second” : doFailerAsync().reflect(),
"Third" : doSomethingElseAsync().reflect()
}).then…
No matter what
Bind lets you share state, w/0 closures
Bind to
State is passed as
‘this’
Enables Code Reuse
Resource management is totes easy with
Using & Disposer
fn getConn() {
return pool.getConnAsync()
.disposer( fn (conn, promise) {
conn.close()
})
}
using( getConn(), fn(conn) {
return conn.queryAsync("…")
}).then( fn (rows) {
log(rows)
})
GC

More Related Content

What's hot

Stay with React.js in 2020
Stay with React.js in 2020Stay with React.js in 2020
Stay with React.js in 2020Jerry Liao
 
Javascript: the important bits
Javascript: the important bitsJavascript: the important bits
Javascript: the important bitsChris Saylor
 
Stubる - Mockingjayを使ったHTTPクライアントのテスト -
Stubる - Mockingjayを使ったHTTPクライアントのテスト -Stubる - Mockingjayを使ったHTTPクライアントのテスト -
Stubる - Mockingjayを使ったHTTPクライアントのテスト -Kenji Tanaka
 
Protocol-Oriented MVVM (extended edition)
Protocol-Oriented MVVM (extended edition)Protocol-Oriented MVVM (extended edition)
Protocol-Oriented MVVM (extended edition)Natasha Murashev
 
Devoxx 15 equals hashcode
Devoxx 15 equals hashcodeDevoxx 15 equals hashcode
Devoxx 15 equals hashcodebleporini
 
The evolution of java script asynchronous calls
The evolution of java script asynchronous callsThe evolution of java script asynchronous calls
The evolution of java script asynchronous callsHuy Hoàng Phạm
 
Swiss army knife Spring
Swiss army knife SpringSwiss army knife Spring
Swiss army knife SpringMario Fusco
 
Event driven javascript
Event driven javascriptEvent driven javascript
Event driven javascriptFrancesca1980
 
Currying and Partial Function Application (PFA)
Currying and Partial Function Application (PFA)Currying and Partial Function Application (PFA)
Currying and Partial Function Application (PFA)Dhaval Dalal
 
How to perform debounce in react
How to perform debounce in reactHow to perform debounce in react
How to perform debounce in reactBOSC Tech Labs
 
Ten useful JavaScript tips & best practices
Ten useful JavaScript tips & best practicesTen useful JavaScript tips & best practices
Ten useful JavaScript tips & best practicesAnkit Rastogi
 
JavaScript Functions
JavaScript FunctionsJavaScript Functions
JavaScript FunctionsColin DeCarlo
 
Effective Java with Groovy - How Language Influences Adoption of Good Practices
Effective Java with Groovy - How Language Influences Adoption of Good PracticesEffective Java with Groovy - How Language Influences Adoption of Good Practices
Effective Java with Groovy - How Language Influences Adoption of Good PracticesNaresha K
 

What's hot (20)

Stay with React.js in 2020
Stay with React.js in 2020Stay with React.js in 2020
Stay with React.js in 2020
 
Javascript: the important bits
Javascript: the important bitsJavascript: the important bits
Javascript: the important bits
 
Stubる - Mockingjayを使ったHTTPクライアントのテスト -
Stubる - Mockingjayを使ったHTTPクライアントのテスト -Stubる - Mockingjayを使ったHTTPクライアントのテスト -
Stubる - Mockingjayを使ったHTTPクライアントのテスト -
 
Protocol-Oriented MVVM (extended edition)
Protocol-Oriented MVVM (extended edition)Protocol-Oriented MVVM (extended edition)
Protocol-Oriented MVVM (extended edition)
 
React lecture
React lectureReact lecture
React lecture
 
Devoxx 15 equals hashcode
Devoxx 15 equals hashcodeDevoxx 15 equals hashcode
Devoxx 15 equals hashcode
 
The evolution of java script asynchronous calls
The evolution of java script asynchronous callsThe evolution of java script asynchronous calls
The evolution of java script asynchronous calls
 
Swiss army knife Spring
Swiss army knife SpringSwiss army knife Spring
Swiss army knife Spring
 
Event driven javascript
Event driven javascriptEvent driven javascript
Event driven javascript
 
SOLID Principles
SOLID PrinciplesSOLID Principles
SOLID Principles
 
Domains!
Domains!Domains!
Domains!
 
Rxjs vienna
Rxjs viennaRxjs vienna
Rxjs vienna
 
Currying and Partial Function Application (PFA)
Currying and Partial Function Application (PFA)Currying and Partial Function Application (PFA)
Currying and Partial Function Application (PFA)
 
How to perform debounce in react
How to perform debounce in reactHow to perform debounce in react
How to perform debounce in react
 
Ten useful JavaScript tips & best practices
Ten useful JavaScript tips & best practicesTen useful JavaScript tips & best practices
Ten useful JavaScript tips & best practices
 
Boot strap.groovy
Boot strap.groovyBoot strap.groovy
Boot strap.groovy
 
Kotlin Generation
Kotlin GenerationKotlin Generation
Kotlin Generation
 
JavaScript Functions
JavaScript FunctionsJavaScript Functions
JavaScript Functions
 
Effective Java with Groovy - How Language Influences Adoption of Good Practices
Effective Java with Groovy - How Language Influences Adoption of Good PracticesEffective Java with Groovy - How Language Influences Adoption of Good Practices
Effective Java with Groovy - How Language Influences Adoption of Good Practices
 
Solid principles
Solid principlesSolid principles
Solid principles
 

Viewers also liked

Promise and Bluebird
Promise and BluebirdPromise and Bluebird
Promise and BluebirdDaniel Ku
 
MeaNstack on Docker
MeaNstack on DockerMeaNstack on Docker
MeaNstack on DockerDaniel Ku
 
Google Analytics
Google AnalyticsGoogle Analytics
Google AnalyticsDaniel Ku
 
Deploying an application with Chef and Docker
Deploying an application with Chef and DockerDeploying an application with Chef and Docker
Deploying an application with Chef and DockerDaniel Ku
 
Getting Started with Redis
Getting Started with RedisGetting Started with Redis
Getting Started with RedisDaniel Ku
 
Object-oriented Javascript
Object-oriented JavascriptObject-oriented Javascript
Object-oriented JavascriptDaniel Ku
 
Indices APIs - Elasticsearch Reference
Indices APIs - Elasticsearch ReferenceIndices APIs - Elasticsearch Reference
Indices APIs - Elasticsearch ReferenceDaniel Ku
 
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
 
ECMAScript 6 and the Node Driver
ECMAScript 6 and the Node DriverECMAScript 6 and the Node Driver
ECMAScript 6 and the Node DriverMongoDB
 

Viewers also liked (10)

Promise and Bluebird
Promise and BluebirdPromise and Bluebird
Promise and Bluebird
 
MeaNstack on Docker
MeaNstack on DockerMeaNstack on Docker
MeaNstack on Docker
 
Google Analytics
Google AnalyticsGoogle Analytics
Google Analytics
 
Deploying an application with Chef and Docker
Deploying an application with Chef and DockerDeploying an application with Chef and Docker
Deploying an application with Chef and Docker
 
Getting Started with Redis
Getting Started with RedisGetting Started with Redis
Getting Started with Redis
 
Object-oriented Javascript
Object-oriented JavascriptObject-oriented Javascript
Object-oriented Javascript
 
Indices APIs - Elasticsearch Reference
Indices APIs - Elasticsearch ReferenceIndices APIs - Elasticsearch Reference
Indices APIs - Elasticsearch Reference
 
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 (...
 
JavaScript Promises
JavaScript PromisesJavaScript Promises
JavaScript Promises
 
ECMAScript 6 and the Node Driver
ECMAScript 6 and the Node DriverECMAScript 6 and the Node Driver
ECMAScript 6 and the Node Driver
 

Similar to Utilizing Bluebird Promises

JavaScript Promises
JavaScript PromisesJavaScript Promises
JavaScript PromisesTomasz Bak
 
Promises - Asynchronous Control Flow
Promises - Asynchronous Control FlowPromises - Asynchronous Control Flow
Promises - Asynchronous Control FlowHenrique Barcelos
 
AngularJS, More Than Directives !
AngularJS, More Than Directives !AngularJS, More Than Directives !
AngularJS, More Than Directives !Gaurav Behere
 
Think Async: Asynchronous Patterns in NodeJS
Think Async: Asynchronous Patterns in NodeJSThink Async: Asynchronous Patterns in NodeJS
Think Async: Asynchronous Patterns in NodeJSAdam L Barrett
 
Better react/redux apps using redux-saga
Better react/redux apps using redux-sagaBetter react/redux apps using redux-saga
Better react/redux apps using redux-sagaYounes (omar) Meliani
 
Async js - Nemetschek Presentaion @ HackBulgaria
Async js - Nemetschek Presentaion @ HackBulgariaAsync js - Nemetschek Presentaion @ HackBulgaria
Async js - Nemetschek Presentaion @ HackBulgariaHackBulgaria
 
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
 
Promises are so passé - Tim Perry - Codemotion Milan 2016
Promises are so passé - Tim Perry - Codemotion Milan 2016Promises are so passé - Tim Perry - Codemotion Milan 2016
Promises are so passé - Tim Perry - Codemotion Milan 2016Codemotion
 
Understanding Asynchronous JavaScript
Understanding Asynchronous JavaScriptUnderstanding Asynchronous JavaScript
Understanding Asynchronous JavaScriptjnewmanux
 
Async Redux Actions With RxJS - React Rally 2016
Async Redux Actions With RxJS - React Rally 2016Async Redux Actions With RxJS - React Rally 2016
Async Redux Actions With RxJS - React Rally 2016Ben Lesh
 
Javascript best practices
Javascript best practicesJavascript best practices
Javascript best practicesManav Gupta
 
Akka Futures and Akka Remoting
Akka Futures  and Akka RemotingAkka Futures  and Akka Remoting
Akka Futures and Akka RemotingKnoldus Inc.
 

Similar to Utilizing Bluebird Promises (20)

You promise?
You promise?You promise?
You promise?
 
JavaScript Promises
JavaScript PromisesJavaScript Promises
JavaScript Promises
 
Promises - Asynchronous Control Flow
Promises - Asynchronous Control FlowPromises - Asynchronous Control Flow
Promises - Asynchronous Control Flow
 
Promises, Promises
Promises, PromisesPromises, Promises
Promises, Promises
 
AngularJS, More Than Directives !
AngularJS, More Than Directives !AngularJS, More Than Directives !
AngularJS, More Than Directives !
 
Think Async: Asynchronous Patterns in NodeJS
Think Async: Asynchronous Patterns in NodeJSThink Async: Asynchronous Patterns in NodeJS
Think Async: Asynchronous Patterns in NodeJS
 
Better react/redux apps using redux-saga
Better react/redux apps using redux-sagaBetter react/redux apps using redux-saga
Better react/redux apps using redux-saga
 
Async js - Nemetschek Presentaion @ HackBulgaria
Async js - Nemetschek Presentaion @ HackBulgariaAsync js - Nemetschek Presentaion @ HackBulgaria
Async js - Nemetschek Presentaion @ HackBulgaria
 
The evolution of asynchronous JavaScript
The evolution of asynchronous JavaScriptThe evolution of asynchronous JavaScript
The evolution of asynchronous 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...
 
Rxjs kyivjs 2015
Rxjs kyivjs 2015Rxjs kyivjs 2015
Rxjs kyivjs 2015
 
Promises are so passé - Tim Perry - Codemotion Milan 2016
Promises are so passé - Tim Perry - Codemotion Milan 2016Promises are so passé - Tim Perry - Codemotion Milan 2016
Promises are so passé - Tim Perry - Codemotion Milan 2016
 
Understanding Asynchronous JavaScript
Understanding Asynchronous JavaScriptUnderstanding Asynchronous JavaScript
Understanding Asynchronous JavaScript
 
JavaScript Neednt Hurt - JavaBin talk
JavaScript Neednt Hurt - JavaBin talkJavaScript Neednt Hurt - JavaBin talk
JavaScript Neednt Hurt - JavaBin talk
 
Async Redux Actions With RxJS - React Rally 2016
Async Redux Actions With RxJS - React Rally 2016Async Redux Actions With RxJS - React Rally 2016
Async Redux Actions With RxJS - React Rally 2016
 
Java scriptconfusingbits
Java scriptconfusingbitsJava scriptconfusingbits
Java scriptconfusingbits
 
Java scriptconfusingbits
Java scriptconfusingbitsJava scriptconfusingbits
Java scriptconfusingbits
 
Javascript best practices
Javascript best practicesJavascript best practices
Javascript best practices
 
Promise is a Promise
Promise is a PromisePromise is a Promise
Promise is a Promise
 
Akka Futures and Akka Remoting
Akka Futures  and Akka RemotingAkka Futures  and Akka Remoting
Akka Futures and Akka Remoting
 

Recently uploaded

KubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghlyKubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghlysanyuktamishra911
 
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Bookingdharasingh5698
 
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...ranjana rawat
 
Unit 1 - Soil Classification and Compaction.pdf
Unit 1 - Soil Classification and Compaction.pdfUnit 1 - Soil Classification and Compaction.pdf
Unit 1 - Soil Classification and Compaction.pdfRagavanV2
 
Generative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPTGenerative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPTbhaskargani46
 
UNIT-V FMM.HYDRAULIC TURBINE - Construction and working
UNIT-V FMM.HYDRAULIC TURBINE - Construction and workingUNIT-V FMM.HYDRAULIC TURBINE - Construction and working
UNIT-V FMM.HYDRAULIC TURBINE - Construction and workingrknatarajan
 
Thermal Engineering Unit - I & II . ppt
Thermal Engineering  Unit - I & II . pptThermal Engineering  Unit - I & II . ppt
Thermal Engineering Unit - I & II . pptDineshKumar4165
 
Extrusion Processes and Their Limitations
Extrusion Processes and Their LimitationsExtrusion Processes and Their Limitations
Extrusion Processes and Their Limitations120cr0395
 
UNIT-IFLUID PROPERTIES & FLOW CHARACTERISTICS
UNIT-IFLUID PROPERTIES & FLOW CHARACTERISTICSUNIT-IFLUID PROPERTIES & FLOW CHARACTERISTICS
UNIT-IFLUID PROPERTIES & FLOW CHARACTERISTICSrknatarajan
 
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdfONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdfKamal Acharya
 
AKTU Computer Networks notes --- Unit 3.pdf
AKTU Computer Networks notes ---  Unit 3.pdfAKTU Computer Networks notes ---  Unit 3.pdf
AKTU Computer Networks notes --- Unit 3.pdfankushspencer015
 
Thermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - VThermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - VDineshKumar4165
 
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...ranjana rawat
 
BSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptx
BSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptxBSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptx
BSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptxfenichawla
 
University management System project report..pdf
University management System project report..pdfUniversity management System project report..pdf
University management System project report..pdfKamal Acharya
 
UNIT-III FMM. DIMENSIONAL ANALYSIS
UNIT-III FMM.        DIMENSIONAL ANALYSISUNIT-III FMM.        DIMENSIONAL ANALYSIS
UNIT-III FMM. DIMENSIONAL ANALYSISrknatarajan
 
chapter 5.pptx: drainage and irrigation engineering
chapter 5.pptx: drainage and irrigation engineeringchapter 5.pptx: drainage and irrigation engineering
chapter 5.pptx: drainage and irrigation engineeringmulugeta48
 

Recently uploaded (20)

Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort ServiceCall Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
 
KubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghlyKubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghly
 
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
 
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
 
Unit 1 - Soil Classification and Compaction.pdf
Unit 1 - Soil Classification and Compaction.pdfUnit 1 - Soil Classification and Compaction.pdf
Unit 1 - Soil Classification and Compaction.pdf
 
Generative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPTGenerative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPT
 
(INDIRA) Call Girl Bhosari Call Now 8617697112 Bhosari Escorts 24x7
(INDIRA) Call Girl Bhosari Call Now 8617697112 Bhosari Escorts 24x7(INDIRA) Call Girl Bhosari Call Now 8617697112 Bhosari Escorts 24x7
(INDIRA) Call Girl Bhosari Call Now 8617697112 Bhosari Escorts 24x7
 
UNIT-V FMM.HYDRAULIC TURBINE - Construction and working
UNIT-V FMM.HYDRAULIC TURBINE - Construction and workingUNIT-V FMM.HYDRAULIC TURBINE - Construction and working
UNIT-V FMM.HYDRAULIC TURBINE - Construction and working
 
Thermal Engineering Unit - I & II . ppt
Thermal Engineering  Unit - I & II . pptThermal Engineering  Unit - I & II . ppt
Thermal Engineering Unit - I & II . ppt
 
Extrusion Processes and Their Limitations
Extrusion Processes and Their LimitationsExtrusion Processes and Their Limitations
Extrusion Processes and Their Limitations
 
UNIT-IFLUID PROPERTIES & FLOW CHARACTERISTICS
UNIT-IFLUID PROPERTIES & FLOW CHARACTERISTICSUNIT-IFLUID PROPERTIES & FLOW CHARACTERISTICS
UNIT-IFLUID PROPERTIES & FLOW CHARACTERISTICS
 
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdfONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
 
AKTU Computer Networks notes --- Unit 3.pdf
AKTU Computer Networks notes ---  Unit 3.pdfAKTU Computer Networks notes ---  Unit 3.pdf
AKTU Computer Networks notes --- Unit 3.pdf
 
Thermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - VThermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - V
 
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
 
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
 
BSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptx
BSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptxBSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptx
BSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptx
 
University management System project report..pdf
University management System project report..pdfUniversity management System project report..pdf
University management System project report..pdf
 
UNIT-III FMM. DIMENSIONAL ANALYSIS
UNIT-III FMM.        DIMENSIONAL ANALYSISUNIT-III FMM.        DIMENSIONAL ANALYSIS
UNIT-III FMM. DIMENSIONAL ANALYSIS
 
chapter 5.pptx: drainage and irrigation engineering
chapter 5.pptx: drainage and irrigation engineeringchapter 5.pptx: drainage and irrigation engineering
chapter 5.pptx: drainage and irrigation engineering
 

Utilizing Bluebird Promises

  • 2. 13 A resolved promise is essentially a “value”
  • 3. A rejected promise is essentially a caught ErrorA rejected promise is essentially a caught Error
  • 4. (error only catches OperationalErrors) These errors jump straight to the next “catch” or “error” .catch(fn ( ) { // handlin’ }) .catch(fn ( ) { // handlin’ }); .then(fn ( ) { // executin’ }) .then(fn ( ) { // executin’ }) getUserAsync({ userID: ‘abc’ }) fn(err) { // handlin’ } fn(err) { // handlin’ } fn(err) { // handlin’ }
  • 5. Promises allow you to create asynchronous “Pipelines” Sending JSON fn(err) { // handlin’ } Error Handler (Generic) Diff’rent 404’d Puppies Got! … then Get all the user’s puppies 404’d User Got! … then Get me the user
  • 6. Creating Promises (A Contrived Example) fn x2Later ( num, callback ) { process.nextTick( fn () { callback( num * 2 ) }) } fn x2Async ( num ) { return new Promise( fn ( resolver, rejector ) { x2Later( num, resolver ) }) }
  • 7. Use Promisify (A Contrived Example) fn x2Later ( num, callback ) { process.nextTick( fn () { callback( num * 2 ) }) } x2Async = Promise.promisify( x2Later )
  • 8. Just use promisifyAll ( Always do this at the root require ) var fs = Promise.promisifyAll(require(‘fs’)) fs.readFileAsync(file)fs.readFile(file, cb) fs.openAsync(file)fs.open(file, cb) fs.renameAsync(old, new)fs.rename(old, new, cb) fs.mkdirAsync(path)fs.mkdir(path, cb)
  • 9. Wrapping non-compliant API’s is easy var getUsersAsync = fn ( userIds ) { return new Promise( fn ( resolve, reject ) { // Noncompliant API uses an object of callbacks getUsers( userIds, { success : fn ( err, data ) { (err) ? reject(err) : resolve(data.users) }, error : fn ( status, obj ) { // TODO (Nicholas): REFACTOR TO BE JSON API COMPLIANT reject( new Promise.OperationalError( status.description ) ) } }) }) }
  • 10. Sometimes you need to wait for two (or more) operations to succeeed Sending JSON Do some logic Join’d promises promise Users Got! … spread Join these two GetUser promises
  • 11. You can easily manage collections of promises ( Also: settle, any, some, props ) all At least one failed All Successful
  • 12. And your functional buddies are here too! ( Also: reduce, each, filter ) map At least one failed All Successful
  • 13. Testing Promises is Easy (With Chai as Promised) ( Thanks to Domenic Denicola, now of Google Chrome team ) .should.eventually.equal( ) .should.eventually.equal( ) .should.be.rejectedWith( ) .should.be.rejectedWith( )
  • 15. Timers let you control when and if a promise fulfills Timeout Delay … is the opposite of ...
  • 16. Bluebird gives you many helpful inspection methods reflect isFulfilled isRejected isPending value reason ? ? ?? ??? ??? Err
  • 17. Reflect is a super powerful generic Settle Promise.props({ "First" : doThingAsync().reflect(), "Second” : doFailerAsync().reflect(), "Third" : doSomethingElseAsync().reflect() }).then… No matter what
  • 18. Bind lets you share state, w/0 closures Bind to State is passed as ‘this’ Enables Code Reuse
  • 19. Resource management is totes easy with Using & Disposer fn getConn() { return pool.getConnAsync() .disposer( fn (conn, promise) { conn.close() }) } using( getConn(), fn(conn) { return conn.queryAsync("…") }).then( fn (rows) { log(rows) }) GC