bluebird.js
A cheatsheet by @rstacruz|Refreshed 7 months ago.Refresh|View source on Github

Also see

Also see

Also see the promise cheatsheet and Bluebird.js API (github.com).

Example

Example

promise
  .then(okFn, errFn)
  .spread(okFn, errFn)        // *
  .catch(errFn)
  .catch(TypeError, errFn)    // *
  .finally(fn)
  .map(function (e) { ··· })  // *
  .each(function (e) { ··· }) // *

Those marked with * are non-standard Promise API that only work with Bluebird promises.

Multiple return values

Multiple return values

.then(function () {
  return [ 'abc', 'def' ]
})
.spread(function (abc, def) {
  ···
})

Use Promise.spread

Multiple promises

Multiple promises

Promise.join(
  getPictures(),
  getMessages(),
  getTweets(),
  function (pics, msgs, tweets) {
    return ···
  }
)

Use Promise.join

Multiple promises (array)

Multiple promises (array)

Promise.all([ promise1, promise2 ])
  .then(results => {
    results[0]
    results[1]
  })

// succeeds if one succeeds first
Promise.any(promises)
  .then(results => {
  })
Promise.map(urls, url => fetch(url))
  .then(···)

Use Promise.map to “promisify” a list of values.

Object

Object

Promise.props({
  photos: get('photos'),
  posts: get('posts')
})
.then(res => {
  res.photos
  res.posts
})

Use Promise.props.

Chain of promises

Chain of promises

function getPhotos() {
  return Promise.try(() => {
    if (err) throw new Error("boo")
    return result
  })
}

getPhotos().then(···)

Use Promise.try.

Node-style functions

Node-style functions

var readFile = Promise.promisify(fs.readFile)
var fs = Promise.promisifyAll(require('fs'))

See Promisification.

Promise-returning methods

Promise-returning methods

User.login = Promise.method((email, password) => {
  if (!valid)
    throw new Error("Email not valid")

  return /* promise */
})

See Promise.method.

Generators

Generators

User.login = Promise.coroutine(function* (email, password) {
  let user = yield User.find({email: email}).fetch()
  return user
})

See Promise.coroutine.