Promises (also known as futures) are a way to manage asynchronous control flow. This deck contains a lot of information on using the bluebird promise library and everything that it gives you.
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
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