Skip to content

Instantly share code, notes, and snippets.

@radiosilence
Created October 1, 2013 15:24
Show Gist options
  • Save radiosilence/6780195 to your computer and use it in GitHub Desktop.
Save radiosilence/6780195 to your computer and use it in GitHub Desktop.
How do I make callback chaining/injection happen in a cleaner/testable way?
var
http = require('http'),
async = require('async'),
printIP = function(cbs, data) {
console.log("Your IP address: " + data.ip);
},
yellIP = function(cbs, data) {
console.log("OI!!! IP!!! " + data.ip);
},
parseJSON = function(cbs, string) {
cbs.shift()(cbs, JSON.parse(string));
},
getIP = function(cbs) {
http.get({
host: 'ip.jsontest.com',
path: '/'
}, function(res) {
var str = '';
res.on('data', function(chunk) {
str += chunk;
});
return res.on('end', function() {
// Shift the first callback off and call it
cbs.shift()(cbs, str);
});
});
};
// Pass in chain of callbacks.
getIP([
parseJSON,
printIP
]);
// Different one!
getIP([
parseJSON,
yellIP,
]);
// Prints, but if I wanted to return the IP address from this, how could I?
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment