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

PDF
JavaScript promise
PDF
Asynchronous programming done right - Node.js
PDF
Callbacks, promises, generators - asynchronous javascript
PPTX
The Promised Land (in Angular)
PPTX
Async Frontiers
PPTX
Promises, promises, and then observables
PPTX
Ian 20150116 java script oop
PDF
How do we use hooks
JavaScript promise
Asynchronous programming done right - Node.js
Callbacks, promises, generators - asynchronous javascript
The Promised Land (in Angular)
Async Frontiers
Promises, promises, and then observables
Ian 20150116 java script oop
How do we use hooks

What's hot (20)

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

Viewers also liked (10)

PDF
Promise and Bluebird
PDF
MeaNstack on Docker
PDF
Google Analytics
PDF
Deploying an application with Chef and Docker
PDF
Getting Started with Redis
PDF
Object-oriented Javascript
PDF
Indices APIs - Elasticsearch Reference
PDF
Beautiful code instead of callback hell using ES6 Generators, Koa, Bluebird (...
PDF
JavaScript Promises
PPTX
ECMAScript 6 and the Node Driver
Promise and Bluebird
MeaNstack on Docker
Google Analytics
Deploying an application with Chef and Docker
Getting Started with Redis
Object-oriented Javascript
Indices APIs - Elasticsearch Reference
Beautiful code instead of callback hell using ES6 Generators, Koa, Bluebird (...
JavaScript Promises
ECMAScript 6 and the Node Driver
Ad

Similar to Utilizing Bluebird Promises (20)

PPT
You promise?
PDF
JavaScript Promises
PDF
Promises - Asynchronous Control Flow
PPTX
Promises, Promises
PPTX
AngularJS, More Than Directives !
PDF
Think Async: Asynchronous Patterns in NodeJS
PDF
Better react/redux apps using redux-saga
PDF
Async js - Nemetschek Presentaion @ HackBulgaria
PDF
The evolution of asynchronous JavaScript
PPTX
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
PDF
Rxjs kyivjs 2015
PDF
Promises are so passé - Tim Perry - Codemotion Milan 2016
PDF
Understanding Asynchronous JavaScript
KEY
JavaScript Neednt Hurt - JavaBin talk
PPTX
Async Redux Actions With RxJS - React Rally 2016
PDF
Java scriptconfusingbits
PDF
Java scriptconfusingbits
PPTX
Javascript best practices
PDF
Promise is a Promise
PDF
Akka Futures and Akka Remoting
You promise?
JavaScript Promises
Promises - Asynchronous Control Flow
Promises, Promises
AngularJS, More Than Directives !
Think Async: Asynchronous Patterns in NodeJS
Better react/redux apps using redux-saga
Async js - Nemetschek Presentaion @ HackBulgaria
The evolution of asynchronous JavaScript
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
Rxjs kyivjs 2015
Promises are so passé - Tim Perry - Codemotion Milan 2016
Understanding Asynchronous JavaScript
JavaScript Neednt Hurt - JavaBin talk
Async Redux Actions With RxJS - React Rally 2016
Java scriptconfusingbits
Java scriptconfusingbits
Javascript best practices
Promise is a Promise
Akka Futures and Akka Remoting

Recently uploaded (20)

PDF
August -2025_Top10 Read_Articles_ijait.pdf
PPTX
6ME3A-Unit-II-Sensors and Actuators_Handouts.pptx
PPTX
Chemical Technological Processes, Feasibility Study and Chemical Process Indu...
PDF
Soil Improvement Techniques Note - Rabbi
PPTX
Module 8- Technological and Communication Skills.pptx
PDF
SMART SIGNAL TIMING FOR URBAN INTERSECTIONS USING REAL-TIME VEHICLE DETECTI...
PDF
Abrasive, erosive and cavitation wear.pdf
PPTX
Current and future trends in Computer Vision.pptx
PPTX
Feature types and data preprocessing steps
PDF
BIO-INSPIRED ARCHITECTURE FOR PARSIMONIOUS CONVERSATIONAL INTELLIGENCE : THE ...
PPTX
tack Data Structure with Array and Linked List Implementation, Push and Pop O...
PPTX
Graph Data Structures with Types, Traversals, Connectivity, and Real-Life App...
PPTX
Amdahl’s law is explained in the above power point presentations
PPT
INTRODUCTION -Data Warehousing and Mining-M.Tech- VTU.ppt
PPTX
ASME PCC-02 TRAINING -DESKTOP-NLE5HNP.pptx
PPTX
Fundamentals of Mechanical Engineering.pptx
PDF
EXPLORING LEARNING ENGAGEMENT FACTORS INFLUENCING BEHAVIORAL, COGNITIVE, AND ...
PDF
Exploratory_Data_Analysis_Fundamentals.pdf
PDF
Influence of Green Infrastructure on Residents’ Endorsement of the New Ecolog...
PPTX
communication and presentation skills 01
August -2025_Top10 Read_Articles_ijait.pdf
6ME3A-Unit-II-Sensors and Actuators_Handouts.pptx
Chemical Technological Processes, Feasibility Study and Chemical Process Indu...
Soil Improvement Techniques Note - Rabbi
Module 8- Technological and Communication Skills.pptx
SMART SIGNAL TIMING FOR URBAN INTERSECTIONS USING REAL-TIME VEHICLE DETECTI...
Abrasive, erosive and cavitation wear.pdf
Current and future trends in Computer Vision.pptx
Feature types and data preprocessing steps
BIO-INSPIRED ARCHITECTURE FOR PARSIMONIOUS CONVERSATIONAL INTELLIGENCE : THE ...
tack Data Structure with Array and Linked List Implementation, Push and Pop O...
Graph Data Structures with Types, Traversals, Connectivity, and Real-Life App...
Amdahl’s law is explained in the above power point presentations
INTRODUCTION -Data Warehousing and Mining-M.Tech- VTU.ppt
ASME PCC-02 TRAINING -DESKTOP-NLE5HNP.pptx
Fundamentals of Mechanical Engineering.pptx
EXPLORING LEARNING ENGAGEMENT FACTORS INFLUENCING BEHAVIORAL, COGNITIVE, AND ...
Exploratory_Data_Analysis_Fundamentals.pdf
Influence of Green Infrastructure on Residents’ Endorsement of the New Ecolog...
communication and presentation skills 01

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