DEV Community

Lam
Lam

Posted on

2 2

Simple Bluebird.Js Cheat Sheet

Reference

Generators

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

See Promise.coroutine.

Promise-returning methods

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

  return /* promise */
})
Enter fullscreen mode Exit fullscreen mode

See Promise.method.

Node-style functions

var readFile = Promise.promisify(fs.readFile)
var fs = Promise.promisifyAll(require('fs'))
Enter fullscreen mode Exit fullscreen mode

See Promisification.

Chain of promises

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

getPhotos().then(···)
Enter fullscreen mode Exit fullscreen mode

Use Promise.try.

Object

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

Use Promise.props.

Multiple promises (array)

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

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

Enter fullscreen mode Exit fullscreen mode

Use Promise.map to "promisify" a list of values.### Multiple promises

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

Use Promise.join

Multiple return values

.then(function () { return [ 'abc', 'def' ] }) 
Enter fullscreen mode Exit fullscreen mode

Use Promise.spread

Example

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

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

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay