2.9 KiB
2.9 KiB
title | category | layout |
---|---|---|
bluebird.js | JavaScript libraries | default-ad |
Also see the promise cheatsheet and Bluebird.js API (github.com). {:.center.brief-intro}
promise
.then(okFn, errFn)
.spread(okFn, errFn) //*
.catch(errFn)
.catch(TypeError, errFn) //*
.finally(fn) //*
.map(function (e) { ... })
.each(function (e) { ... })
Multiple return values
Use Promise.spread.
.then(function () {
return [ 'abc', 'def' ];
})
.spread(function (abc, def) {
...
});
Multiple promises
Use Promise.join.
Promise.join(
getPictures(),
getMessages(),
getTweets(),
function (pics, msgs, tweets) {
return ...;
}
)
Multiple promises (array)
- Promise.all([p]) - expect all to pass
- Promise.some([p], count) - expect
count
to pass - Promise.any([p]) - same as
some([p], 1)
- Promise.race([p], count) - use
.any
instead - Promise.map([p], fn, options) - supports concurrency
Promise.all([ promise1, promise2 ])
.then(results => {
results[0]
results[1]
})
// succeeds if one succeeds first
Promise.any(promises)
.then(results => {
})
Use Promise.map to "promisify" a list of values.
Promise.map(urls, url => fetch(url))
.then(...)
Object
Usually it's better to use .join
, but whatever.
Promise.props({
photos: get('photos'),
posts: get('posts')
})
.then(res => {
res.photos
res.posts
})
Chain of promises
Use Promise.try.
function getPhotos() {
return Promise.try(() => {
if (err) throw new Error("boo")
return result
})
}
getPhotos().then(...)
Using Node-style functions
See Promisification.
var readFile = Promise.promisify(fs.readFile)
var fs = Promise.promisifyAll(require('fs'))
Promise-returning methods
See Promise.method.
User.login = Promise.method((email, password) => {
if (!valid)
throw new Error("Email not valid")
return /* promise */
});
Generators
See Promise.coroutine.
User.login = Promise.coroutine(function* (email, password) {
let user = yield User.find({email: email}).fetch()
return user
})