Bluebird Cheat Sheet

From WikiOD

Here is the cheatsheat of Bluebird and basic guide on how to use Bluebird

Also see[edit | edit source]

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

Example[edit | edit source]

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[edit | edit source]

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

{: data-line=“4”}

Use Promise.spread

Multiple promises[edit | edit source]

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

{: data-line=“1”}

Use Promise.join

Multiple promises (array)[edit | edit source]

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

// succeeds if one succeeds first
Promise.any(promises)
  .then(results => {
  })

{: data-line=“1,8”}

Promise.map(urls, url => fetch(url))
  .then(···)

{: data-line=“1”}

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

Object[edit | edit source]

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

{: data-line=“1”}

Use Promise.props.

Chain of promises[edit | edit source]

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

getPhotos().then(···)

{: data-line=“2”}

Use Promise.try.

Node-style functions[edit | edit source]

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

{: data-line=“2”}

See Promisification.

Promise-returning methods[edit | edit source]

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

  return /* promise */
})

{: data-line=“1”}

See Promise.method.

Generators[edit | edit source]

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

{: data-line=“1”}

See Promise.coroutine.

Reference[edit | edit source]

http://bluebirdjs.com/docs/api-reference.html

Credit:rstacruz