Skip to content

Instantly share code, notes, and snippets.

@jcoglan
Created March 11, 2011 01:09
Show Gist options
  • Star 16 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save jcoglan/865294 to your computer and use it in GitHub Desktop.
Save jcoglan/865294 to your computer and use it in GitHub Desktop.
JSCLASS_PATH = 'build/min';
require('./' + JSCLASS_PATH + '/loader');
JS.require('JS.Deferrable');
Promise = new JS.Class({
include: JS.Deferrable,
initialize: function(value) {
if (value !== undefined) this.succeed(value);
}
});
var fs = require('fs'),
url = require('url'),
http = require('http'),
sys = require('sys');
// pipe :: m a -> [a -> m b] -> m b
var pipe = function(x, functions) {
for (var i = 0, n = functions.length; i < n; i++) {
x = bind(x, functions[i]);
}
return x;
};
// unit :: a -> Promise a
var unit = function(x) {
return new Promise(x);
};
// bind :: Promise a -> (a -> Promise b) -> Promise b
var bind = function(input, f) {
var output = new Promise();
input.callback(function(x) {
f(x).callback(function(y) {
output.succeed(y);
});
});
return output;
};
// readFile :: String -> Promise String
var readFile = function(path) {
var promise = new Promise();
fs.readFile(path, function(err, content) {
promise.succeed(content);
});
return promise;
};
// getUrl :: String -> Promise URI
var getUrl = function(json) {
var uri = url.parse(JSON.parse(json).url);
return new Promise(uri);
};
// httpGet :: URI -> Promise Response
var httpGet = function(uri) {
var client = http.createClient(80, uri.hostname),
request = client.request('GET', uri.pathname, {'Host': uri.hostname}),
promise = new Promise();
request.addListener('response', function(response) {
promise.succeed(response);
});
request.end();
return promise;
};
// responseBody :: Response -> Promise String
var responseBody = function(response) {
var promise = new Promise(),
body = '';
response.addListener('data', function(c) { body += c });
response.addListener('end', function() {
promise.succeed(body);
});
return promise;
};
// print :: String -> Promise null
var print = function(string) {
return new Promise(sys.puts(string));
};
pipe(unit(__dirname + '/urls.json'),
[ readFile,
getUrl,
httpGet,
responseBody,
print ]);
{"url":"http://github.com/api/v2/json/user/show/jcoglan"}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment