Created
October 1, 2013 15:24
-
-
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?
This file contains hidden or 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
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