This commit is contained in:
Rico Sta. Cruz 2015-04-18 03:17:51 +08:00
parent a0c77549bd
commit 981819454a
1 changed files with 44 additions and 9 deletions

View File

@ -3,7 +3,7 @@ title: bluebird.js
layout: default layout: default
--- ---
Also see the [promise cheatsheet](promise.html). Also see the [promise cheatsheet](promise.html) and [Bluebird.js API](https://github.com/petkaantonov/bluebird/blob/master/API.md) (github.com).
{:.center.brief-intro} {:.center.brief-intro}
```js ```js
@ -17,14 +17,51 @@ promise
.each(function (e) { ... }) .each(function (e) { ... })
``` ```
### Simultaneous promises (array) ----
### Multiple return values
Use [Promise.spread](https://github.com/petkaantonov/bluebird/blob/master/API.md#spreadfunction-fulfilledhandler--function-rejectedhandler----promise).
```js ```js
Promise.any(promises) // succeeds if one succeeds first .then(function () {
return [ 'abc', 'def' ];
})
.spread(function (abc, def) {
...
});
```
### Multiple promises
Use [Promise.join](https://github.com/petkaantonov/bluebird/blob/master/API.md#promisejoinpromisethenablevalue-promises-function-handler---promise) for fixed number of multiple promises.
```js
Promise.join(
getPictures(),
getMessages(),
getTweets(),
function (pics, msgs, tweets) {
return ...;
}
)
```
### Multiple promises (array)
Use `.all`, `.any`, `.race`, or `.some`.
```js
Promise.all([ pro1, pro2 ])
.then(function (results) {
results[0]
results[1]
})
// succeeds if one succeeds first
Promise.any(promises)
.then(...) .then(...)
``` ```
### Simultaneous promises (object) ### Object
Usually it's better to use `.join`, but whatever.
```js ```js
Promise.props({ Promise.props({
@ -38,6 +75,7 @@ Promise.props({
``` ```
### Chain of promises ### Chain of promises
Use [Promise.try](https://github.com/petkaantonov/bluebird/blob/master/API.md#promisetryfunction-fn--arraydynamicdynamic-arguments--dynamic-ctx----promise) to start a chain.
```js ```js
function getPhotos() { function getPhotos() {
@ -50,13 +88,10 @@ function getPhotos() {
getPhotos().then(...) getPhotos().then(...)
``` ```
### Working with node-style functions ### Using Node-style functions
See [Promisification](https://github.com/petkaantonov/bluebird/blob/master/API.md#promisification) API.
```js ```js
var readFile = Promise.promisify(fs.readFile); var readFile = Promise.promisify(fs.readFile);
var fs = Promise.promisifyAll(require('fs')); var fs = Promise.promisifyAll(require('fs'));
``` ```
## References
* [Bluebird API](https://github.com/petkaantonov/bluebird/blob/master/API.md) (github.com)