title | layout |
---|---|
bluebird.js |
default |
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) { ... })
Use Promise.spread.
.then(function () {
return [ 'abc', 'def' ];
})
.spread(function (abc, def) {
...
});
Use Promise.join for fixed number of multiple promises.
Promise.join(
getPictures(),
getMessages(),
getTweets(),
function (pics, msgs, tweets) {
return ...;
}
)
Use .all
, .any
, .race
, or .some
.
Promise.all([ promise1, promise2 ])
.then(function (results) {
results[0]
results[1]
})
// succeeds if one succeeds first
Promise.any(promises)
.then(function (result) {
})
Usually it's better to use .join
, but whatever.
Promise.props({
photos: get('photos'),
posts: get('posts')
})
.then(function (res) {
res.photos
res.posts
})
Use Promise.try to start a chain.
function getPhotos() {
return Promise.try(function () {
if (err) throw new Error("boo");
return result;
});
}
getPhotos().then(...)
See Promisification API.
var readFile = Promise.promisify(fs.readFile);
var fs = Promise.promisifyAll(require('fs'));
See Promise.method to allow return
ing values that will be promise resolutions.
User.login = Promise.method(function(email, password) {
if (!valid)
throw new Error("Email not valid");
return /* promise */;
});
See Promise.coroutine.
User.login = Promise.coroutine(function* (email, password) {
let user = yield User.find({email: email}).fetch();
return user;
});