Skip to content

Instantly share code, notes, and snippets.

@zhangchiqing
Created November 13, 2016 16:32
Show Gist options
  • Save zhangchiqing/ce9d9893d7dfda7cb1b1ea000c276439 to your computer and use it in GitHub Desktop.
Save zhangchiqing/ce9d9893d7dfda7cb1b1ea000c276439 to your computer and use it in GitHub Desktop.
An example of async programming with bluebird-promisell - Get Tweets by UserId
var P = require('bluebird-promisell');
var R = require('ramda');
var S = require('./service');
// S.getTweets :: UserId -> Promise [Tweet]
// S.getUserName :: UserId -> Promise String
// S.getUserPhoto :: UserId -> Promise String
// makeUser :: (UserId, String, String) -> User
var makeUser = function(id, name, photo) {
return { id: id, name: name, photo: photo };
};
// selectUserId :: Tweet -> UserId
var selectUserId = function(tweet) {
return tweet.userId;
};
// selectMessage :: Tweet -> String
var selectMessage = function(tweet) {
return tweet.msg;
};
// getUser :: UserId -> Promise User
var getUser = function(userId) {
// Promise String
var nameP = S.getUserName(userId);
// Promise String
var photoP = S.getUserPhoto(userId);
return P.liftp3(makeUser)(P.purep(userId), nameP, photoP);
};
// getTweetsByUserId :: UserId -> Promise [String, User]
var getTweetByUserId = function(theId) {
// Promise [Tweet]
var tweetsP = S.getTweets(theId);
// UserId -> Promise User
var getUserCached = R.once(getUser);
// Tweet -> Promise [String, User]
var getTweetByUserId = function(tweet) {
// UserId
var userId = selectUserId(tweet);
// String
var message = selectMessage(tweet);
// Promise User
var cachedUserP = getUserCached(userId);
return P.liftp2(R.pair)(P.purep(message), cachedUserP);
};
return P.liftp1(P.traversep(getTweetByUserId))(tweetsP);
};
getTweetsByUserId(1)
.then(function(tweets) {
console.log('tweets:', tweets);
})
.catch(function(err) {
console.log('fail to fetch tweets', err);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment