Top Banner
Unfullled (Newborn) Promise Fullled (Resolved) Promise Failed (Rejected) Promise Promises Crash Course Nicholas van de Walle
19

Utilizing Bluebird Promises

Jul 15, 2015

Download

Engineering

Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Utilizing Bluebird Promises

Unfulfilled(Newborn)

Promise

Fulfilled (Resolved) Promise

Failed (Rejected) PromisePromises Crash Course

Nicholas van de Walle

Page 2: Utilizing Bluebird Promises

13

A resolved promise is essentially a “value”

Page 3: Utilizing Bluebird Promises

A rejected promise is essentially a caught ErrorA rejected promise is essentially a caught Error

Page 4: Utilizing Bluebird Promises

(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’}

Page 5: Utilizing Bluebird Promises

Promises allow you to create asynchronous “Pipelines”

Sending JSON

fn(err) { // handlin’}

Error Handler(Generic)

Diff ’rent404’d

Puppies Got! … then

Get all the user’s puppies

404’d User Got! … then

Get me the user

Page 6: Utilizing Bluebird Promises

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

Page 7: Utilizing Bluebird Promises

Use Promisify(A Contrived Example)

fn x2Later ( num, callback ) { process.nextTick( fn () { callback( num * 2 ) })}

x2Async = Promise.promisify( x2Later )

Page 8: Utilizing Bluebird Promises

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)

Page 9: Utilizing Bluebird Promises

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

}

})

})

}

Page 10: Utilizing Bluebird Promises

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

Page 11: Utilizing Bluebird Promises

You can easily manage collections of promises

( Also: settle, any, some, props )

all

At least one failed

All Successful

Page 12: Utilizing Bluebird Promises

And your functional buddies are here too!

( Also: reduce, each, filter )

map

At least one failed

All Successful

Page 13: Utilizing Bluebird Promises

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

Page 14: Utilizing Bluebird Promises

Advanced Concepts

Timers

Statefulness &Context

Resource Management

Inspection

Page 15: Utilizing Bluebird Promises

Timers let you control when and if a promise fulfills

Timeout

Delay

… is the opposite of ...

Page 16: Utilizing Bluebird Promises

Bluebird gives you many helpful inspection methods

reflect

isFulfilled

isRejected

isPending

value

reason

?

?

??

??????

Err

Page 17: Utilizing Bluebird Promises

Reflect is a super powerful generic Settle

Promise.props({

"First" : doThingAsync().reflect(),

"Second” : doFailerAsync().reflect(),

"Third" : doSomethingElseAsync().reflect()

}).then…

No matter what

Page 18: Utilizing Bluebird Promises

Bind lets you share state, w/0 closures

Bind to

State is passed as ‘this’

Enables Code Reuse

Page 19: Utilizing Bluebird Promises

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