I am writing an API wrapper in NodeJs, and am getting hung up on trying to cleanly handle the response from http.get(). The problem's root is that I hate the unclean coding style in all tutorials where the callback method is defined anonymously inline.
// Bad. Can get ugly if the handle function has multiple lines or nested callbacks
http.get("www.example.com", function(response){/* handle response */});
// Better. Follows clean-code guidelines. Code is more reusable. Etc
var handleResponse = function(response){
// handle response
}
http.get("www.example.com", handleResponse);
While I like the latter so much more, I can't seem to pass extra parameters to handleResponse, specifically the callback that I want handleResponse to call.
What I have currently that works:
module.exports = function() {
return {
apiGet: function(url, callback) {
http.get(url, function(response) {
var result = handleResponse(response);
callback(null, result);
});
}
}
}
What I want to have (but doesn't work)
module.exports = function() {
var handleResponse = function(response) {
var result = handleResponse(response);
callback(null, result);
};
return {
apiGet: function(url, callback) {
http.get(url, handleResponse);
}
}
}
The problem with this code is that callback is not defined in the method handleResponse(). I can't seem to get around this.
Things I've tried.
// hoping extra parameters get passed to function. Nope.
return {
http.get(url, handleResponse, callback);
}
// Trying out a suggestion from a random blog I found while googling for an answer. Nope.
return {
http.get(url, handleResponse.bind({callback: callback});
}