项目作者: zhangchiqing

项目描述 :
A practical functional programming library for promises
高级语言: JavaScript
项目地址: git://github.com/zhangchiqing/bluebird-promisell.git
创建时间: 2016-04-15T15:24:40Z
项目社区:https://github.com/zhangchiqing/bluebird-promisell

开源协议:MIT License

下载


bluebird-promisell

A functional programming library for promises.

bluebird-promisell provides a set of composable functions that allows you to write flat async code with promises.

Usage

Write flat async code with “liftp”

Let’s say we have the following sync code to get a list of userId.

  1. var getToken = function() { return 'token'; };
  2. var getSecret = function() { return 'secret'; };
  3. var getUserIds = function(token, secret) {
  4. return [1, 2, 3];
  5. };
  6. // Token
  7. var token = getToken();
  8. // Secret
  9. var secret = getSecret();
  10. // [UserId]
  11. var userIds = getUserIds(token, secret);
  12. console.log(userIds); // [1, 2, 3]

Now, if the sub functions getToken, getSecret, getUserIds becomes async (all return Promise),
the only change we need to make is “lifting” getUserIds with liftp.

  1. var Promise = require('bluebird');
  2. var P = require('bluebird-promisell');
  3. var getToken = function() { return Promise.resolve('token'); };
  4. var getSecret = function() { return Promise.resolve('secret'); };
  5. var getUserIds = function(token, secret) {
  6. return Promise.resolve([1, 2, 3]);
  7. };
  8. // Promise Token
  9. var tokenP = getToken();
  10. // Promise Secret
  11. var secretP = getSecret();
  12. // Promise [UserId]
  13. var userIdsP = P.liftp(getUserIds)(tokenP, secretP);
  14. userIdsP.then(console.log); // [1, 2, 3]

Now the code runs async, but it reads like sync code.

Making async calls in parallel with “traversep”

  1. var getPhotoByUserId = function(userId) {
  2. if (userId === 1) {
  3. return ':)';
  4. } else if (userId === 2) {
  5. return ':D';
  6. } else {
  7. return ':-|';
  8. }
  9. };
  10. // Promise Token
  11. var tokenP = getToken();
  12. // Promise Secret
  13. var secretP = getSecret();
  14. // Promise [UserId]
  15. var userIdsP = P.liftp(getUserIds)(tokenP, secretP);
  16. // Promise [Photo]
  17. var photosP = P.traversep(getPhotoByUserId)(userIdsP);
  18. photosP.then(console.log); // [":)", ":D", ":-|"]

Making async calls sequentially with “foldp”

  1. // Promise [UserId]
  2. var userIdsP = P.liftp(getUserIds)(tokenP, secretP);
  3. // [Photo] -> Photo -> [Photo]
  4. var appendPhotos = function(photos, photo) {
  5. return photos.concat([photo]);
  6. };
  7. // Promise [Photo]
  8. var photosP = P.foldp(function(photos, userId) {
  9. // Promise Photo
  10. var photoP = getPhotoByUserId(userId);
  11. return P.liftp(appendPhotos)(P.purep(photos), photoP); // `P.purep` is equivalent to `Promise.resolve`
  12. })([])(userIdsP);
  13. photosP.then(console.log); // [":)", ":D", ":-|"]

The above code will fetch photo by userId sequentially. If it fails to fetch the first photo,
it will reject the promise without fetching next photo.
And it will resolve the promise once all the photos have been fetched.

Wait until the second async call to finish, then return the value of the first async call

Let’s say we want to send an email with all the photos, and wait until the email has been sent,
then resolve the promise with the photos

With firstp, we can wait until the email has been sent, and return the result of photos which
is from the first promise.

  1. var sendEmailWithPhotos = function(photos) {
  2. return Promise.resolve('The email has been sent');
  3. };
  4. // Promise [Photo]
  5. var photosP = P.foldp(function(photos, userId) {
  6. // Promise Photo
  7. var photoP = getPhotoByUserId(userId);
  8. return P.liftp(appendPhotos)(P.purep(photos), photoP); // `P.purep` is equivalent to `Promise.resolve`
  9. })([])(userIdsP);
  10. // Promise String
  11. var sentP = P.liftp1(sendEmailWithPhotos)(photosP);
  12. // ^^^^^^^^ P.liftp1 is equivalent to P.liftp when there is only one promise to resolve.
  13. // But P.liftp1 has better performance than P.liftp.
  14. P.first(photosP, sentP).then(console.log); // [":)", ":D", ":-|"]

API

purep :: a -> Promise a

Takes any value, returns a resolved Promise with that value

  1. > purep(3).then(console.log)
  2. promise
  3. 3

fmapp :: (a -> b) -> Promise a -> Promise b

Transforms a Promise of value a into a Promise of value b

  1. > fmapp(function(a) { return a + 3; }, Promise.resolve(4)).then(console.log)
  2. promise
  3. 7

voidp :: Promise a -> Promise undefined

Takes a Promise, returns a Promise that resolves with undefined when the input promise is resolved,
or reject with the same error when the input promise is rejected.

  1. > voidp(purep(12)).then(console.log)
  2. promise
  3. undefined

sequencep :: Array Promise a -> Promise Array a

Transforms an array of Promise of value a into a Promise of array of a.

  1. > sequencep([Promise.resolve(3), Promise.resolve(4)]).then(console.log)
  2. promise
  3. [3, 4]

traversep :: (a -> Promise b) -> Array a -> Promise Array b

Maps a function that takes a value a and returns a Promise of value b over an array of value a,
then use sequencep to transform the array of Promise b into a Promise of array b

  1. > traversep(function(a) { return Promise.resolve(a + 3); })(
  2. [2, 3, 4])
  3. promise
  4. [5, 6, 7]

pipep :: [(a -> Promise b), (b -> Promise c), … (m -> Promise n)] -> a -> Promise n

Performs left-to-right composition of an array of Promise-returning functions.

  1. > pipep([
  2. function(a) { return Promise.resolve(a + 3); },
  3. function(b) { return Promise.resolve(b * 10); },
  4. ])(6);
  5. promise
  6. 90

liftp :: (a -> b -> … n -> x) -> Promise a -> Promise b -> … -> Promise n -> Promise x

Takes a function so that this function is able to read input values from resolved Promises,
and return a Promise that will resolve with the output value of that function.

  1. > liftp(function(a, b, c) { return (a + b) * c; })(
  2. Promise.resolve(3),
  3. Promise.resolve(4),
  4. Promise.resolve(5));
  5. promise
  6. 35

liftp1 :: (a -> b) -> Promise a -> Promise b

Takes a function and apply this function to the resolved Promise value, and return
a Promise that will resolve with the output of that function.

  1. > liftp1(function(user) {
  2. return user.email;
  3. })(Promise.resolve({ email: 'abc@example.com' }));
  4. promise
  5. abc@example.com

firstp :: Promise a -> Promise b -> Promise a

Takes two Promises and return the first if both of them are resolved

  1. > firstp(Promise.resolve(1), Promise.resolve(2))
  2. promise
  3. 1
  4. > firstp(Promise.resolve(1), Promise.reject(new Error(3)))
  5. promise
  6. Error 3

secondp :: Promise a -> Promise b -> Promise b

Takes two Promises and return the second if both of them are resolved

  1. > secondp(Promise.resolve(1), Promise.resolve(2))
  2. promise
  3. 2
  4. > secondp(Promise.resolve(1), Promise.reject(new Error(3)))
  5. promise
  6. Error 3

filterp :: (a -> Promise Boolean) -> Array a -> Promise Array a

Takes a predicat that returns a Promise and an array of a, returns a Promise of array a
which satisfy the predicate.

  1. > filterp(function(a) { return Promise.resolve(a > 3); })([2, 3, 4])
  2. promise
  3. [4]

foldp :: (b -> a -> Promise b) -> b -> Array a -> Promise b

Returns a Promise of value b by iterating over an array of value a, successively
calling the iterator function and passing it an accumulator value of value b,
and the current value from the array, and then waiting until the promise resolved,
then passing the result to the next call.

foldp resolves promises sequentially

  1. > foldp(function(b, a) { return Promise.resolve(b + a); })(1)([2, 3, 4])
  2. promise
  3. 10

unfold :: (a -> Promise [b, a]?) -> a -> Promise [b]

Builds a list from a seed value. Accepts an iterator function, which takes the seed and return a Promise.
If the Promise resolves to a false value, it will return the list.
If the Promise resolves to a pair, the first item will be appended to the list and the second item will be used as the new seed in the next call to the iterator function.

  1. > unfold(function(a) {
  2. return a > 5 ? Promise.resolve(false) : Promise.resolve([a, a + 1]);
  3. })(1);
  4. promise
  5. [1,2,3,4,5]

mapError :: (Error -> Error) -> Promise a -> Promise a

Transform the rejected Error.

  1. > mapError(function(err) {
  2. var newError = new Error(err.message);
  3. newError.status = 400;
  4. return newError;
  5. })(Promise.reject(new Error('Not Found')));
  6. rejected promise

resolveError :: (Error -> b) -> Promise a -> Promise b

Recover from a rejected Promise

  1. > resolveError(function(err) {
  2. return false;
  3. });

promise
false

toPromise :: ((a -> Boolean), (a -> Error)) -> a -> Promise a

Takes a predict function and a toError function, return a curried
function that can take a value and return a Promise.
If this value passes the predict, then return a resolved Promise with
that value, otherwise pass the value to the toError function, and
return a rejected Promise with the output of the toError function.

  1. var validateGreaterThan0 = toPromise(function(a) {
  2. return a > 0;
  3. }, function(a) {
  4. return new Error('value is not greater than 0');
  5. });
  6. > validateGreaterThan0(10)
  7. promise
  8. 10
  9. > validateGreaterThan0(-10)
  10. rejected promise
  11. Error 'value is not greater than 0'

bimap :: (a -> Promise b) -> (Error -> Promise b) -> Promise a -> Promise b

Takes two functions and return a function that can take a Promise and return a Promise.
If the received Promise is resolved, the first function will be used to map over the resolved value;
If the received Promise is rejected, the second function will be used to map over the Error.

Like Promise.prototype.then function, but takes functions first.

  1. var add1OrReject = bimap(
  2. function(n) { return n + 1; },
  3. function(error) {
  4. return new Error('can not add value for ' + error.message);
  5. }
  6. );
  7. > add1OrReject(P.purep(2))
  8. promise
  9. 3
  10. > add1OrReject(Promise.reject(new Error('NaN')));
  11. promise
  12. 'can not add value for NaN'