-
-
Save Gozala/5292787 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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