Skip to content

Latest commit

 

History

History
120 lines (98 loc) · 2.69 KB

bluebird.md

File metadata and controls

120 lines (98 loc) · 2.69 KB
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) { ... })

Multiple return values

Use Promise.spread.

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

Multiple promises

Use Promise.join for fixed number of multiple promises.

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

Multiple promises (array)

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) {
  })

Object

Usually it's better to use .join, but whatever.

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

Chain of promises

Use Promise.try to start a chain.

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

getPhotos().then(...)

Using Node-style functions

See Promisification API.

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

Promise-returning methods

See Promise.method to allow returning values that will be promise resolutions.

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

  return /* promise */;
});

Generators

See Promise.coroutine.

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