Bluebird is a high-performance, feature-packed Promise library for JavaScript and Node.js.
Method Chaining Overview
promise
.then(okFn, errFn)
.spread(okFn, errFn) // * Unpacks array into arguments
.catch(errFn)
.catch(TypeError, errFn) // * Filtered error catch
.finally(fn)
.map(function (e) { ... }) // * Iterate concurrently
.each(function (e) { ... }) // * Iterate sequentially
Methods marked with * are Bluebird-specific extensions beyond the standard ES6 Promise specification.
Multiple Arguments & Spreading
Promise.resolve(['foo', 'bar'])
.spread((item1, item2) => {
console.log(item1, item2); // 'foo', 'bar'
});
See: Promise.spread
Combining Fixed Promises (Promise.join)
Coordinates multiple independent promises with a fixed signature:
Promise.join(
getPictures(),
getMessages(),
getTweets(),
(pics, msgs, tweets) => {
return { pics, msgs, tweets };
}
);
See: Promise.join
Array Collection Methods
Promise.all([p]): Resolves when all promises resolve, or rejects immediately on first error.Promise.some([p], count): Resolves whencountpromises settle successfully.Promise.any([p]): Resolves as soon as any single promise settles (equivalent tosome(p, 1)).Promise.map(array, fn, { concurrency: 5 }): Maps items with controlled concurrency.
Promise.map(urls, url => fetch(url), { concurrency: 3 })
.then(responses => {
// Process responses with max 3 simultaneous requests
});
Object Promises (Promise.props)
Resolves an object containing promise values into an object with resolved properties:
Promise.props({
photos: getPhotos(),
posts: getPosts()
}).then(result => {
console.log(result.photos, result.posts);
});
Promisification
Convert legacy Node.js callback-style functions ((err, result) => ...) into promises:
const fs = require('fs');
const Promise = require('bluebird');
// Promisify a single function
const readFile = Promise.promisify(fs.readFile);
// Promisify an entire module
Promise.promisifyAll(fs);
// Now fs.readFileAsync is available
Coroutines (Generators)
const loginUser = Promise.coroutine(function* (email, password) {
const user = yield User.findOne({ email }).exec();
const valid = yield user.comparePassword(password);
if (!valid) throw new Error('Invalid credentials');
return user;
});