Skip to content

Instantly share code, notes, and snippets.

@Gozala
Forked from jcoglan/tweets.js
Last active December 15, 2015 16:59
Show Gist options
  • Save Gozala/5292787 to your computer and use it in GitHub Desktop.
Save Gozala/5292787 to your computer and use it in GitHub Desktop.
// This is in response to https://gist.github.com/Peeja/5284697.
// Peeja wanted to know how to convert some callback-based code to functional
// style using promises.
var Promise = require('rsvp').Promise;
var ids = [1,2,3,4,5,6];
// If this were synchronous, we'd simply write:
// getTweet :: ID -> Tweet
var getTweet = function(id) { return 'Tweet text ' + id };
// upcase :: Tweet -> String
var upcase = function(tweet) { return tweet.toUpperCase() };
var rotten = ids.map(function(id) {
return upcase(getTweet(id));
});
// Or, to put it in the form of a pipeline with two map calls:
var rotten = ids.map(getTweet).map(upcase);
console.log(rotten);
// How about we simply use promised decorator instead of introducing
// more and more promise spicific util functions. That way one can
// just decorate existing sync code and that's it!
var getTweet = function(id) {
var promise = new Promise();
setTimeout(function() { promise.resolve('Tweet text ' + id) }, 500);
return promise;
};
// just decorate our sync function
var upcase = promised(function(tweet) { return tweet.toUpperCase() });
// keep the rest same
var rotten = ids.map(getTweet).map(upcase);
// make async logger :)
var print = promised(console.log);
// print all the values
print.apply(0, rotten);
// For details on `promised` see:
// https://github.com/Gozala/micro-promise/blob/master/core.js#L194-L217
// I also have written more detailed post about this
// a while ago:
// http://jeditoolkit.com/2012/04/26/code-logic-not-mechanics.html#post
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment