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

Javascript: the important bits
Javascript: the important bitsJavascript: the important bits
Javascript: the important bits
Chris Saylor
 
Devoxx 15 equals hashcode
Devoxx 15 equals hashcodeDevoxx 15 equals hashcode
Devoxx 15 equals hashcode
bleporini
 
Swiss army knife Spring
Swiss army knife SpringSwiss army knife Spring
Swiss army knife Spring
Mario Fusco
 

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

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 best practices
Javascript best practicesJavascript best practices
Javascript best practices
Manav Gupta
 

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

Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Christo Ananth
 
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Dr.Costas Sachpazis
 
Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar ≼🔝 Delhi door step de...
Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar  ≼🔝 Delhi door step de...Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar  ≼🔝 Delhi door step de...
Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar ≼🔝 Delhi door step de...
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Christo Ananth
 

Recently uploaded (20)

(INDIRA) Call Girl Meerut Call Now 8617697112 Meerut Escorts 24x7
(INDIRA) Call Girl Meerut Call Now 8617697112 Meerut Escorts 24x7(INDIRA) Call Girl Meerut Call Now 8617697112 Meerut Escorts 24x7
(INDIRA) Call Girl Meerut Call Now 8617697112 Meerut Escorts 24x7
 
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
 
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
 
Call Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance BookingCall Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance Booking
 
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...
 
UNIT-II FMM-Flow Through Circular Conduits
UNIT-II FMM-Flow Through Circular ConduitsUNIT-II FMM-Flow Through Circular Conduits
UNIT-II FMM-Flow Through Circular Conduits
 
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
 
Call for Papers - International Journal of Intelligent Systems and Applicatio...
Call for Papers - International Journal of Intelligent Systems and Applicatio...Call for Papers - International Journal of Intelligent Systems and Applicatio...
Call for Papers - International Journal of Intelligent Systems and Applicatio...
 
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...
 
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
 
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
 
(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
 
Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar ≼🔝 Delhi door step de...
Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar  ≼🔝 Delhi door step de...Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar  ≼🔝 Delhi door step de...
Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar ≼🔝 Delhi door step de...
 
NFPA 5000 2024 standard .
NFPA 5000 2024 standard                                  .NFPA 5000 2024 standard                                  .
NFPA 5000 2024 standard .
 
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...
 
Thermal Engineering Unit - I & II . ppt
Thermal Engineering  Unit - I & II . pptThermal Engineering  Unit - I & II . ppt
Thermal Engineering Unit - I & II . ppt
 
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
 
University management System project report..pdf
University management System project report..pdfUniversity management System project report..pdf
University management System project report..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
 
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