javascript - Pass extra parameter to NodeJs Http callback method -
this question has answer here:
- pass argument callback function 3 answers
i writing api wrapper in nodejs, , getting hung on trying cleanly handle response http.get(). problem's root hate unclean coding style in tutorials callback method defined anonymously inline.
// bad. can ugly if handle function has multiple lines or nested callbacks http.get("www.example.com", function(response){/* handle response */}); // better. follows clean-code guidelines. code more reusable. etc var handleresponse = function(response){ // handle response } http.get("www.example.com", handleresponse);
while latter more, can't seem pass parameters handleresponse, callback want handleresponse call.
what have works:
module.exports = function() { return { apiget: function(url, callback) { http.get(url, function(response) { var result = handleresponse(response); callback(null, result); }); } } }
what want 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 code callback not defined in method handleresponse(). can't seem around this.
things i've tried.
// hoping parameters passed function. nope. return { http.get(url, handleresponse, callback); } // trying out suggestion random blog found while googling answer. nope. return { http.get(url, handleresponse.bind({callback: callback}); }
if have function who's main job pass on control flow other functions perhaps instead of writing handleresponse()
function should consider writing makeresponsehandler()
. basically, use function factory:
function makeresponsehandler (callback) { return function (response) { // deal response here callback(null, result); } }; return { apiget: function(url, callback) { http.get(url, makeresponsehandler(callback)); } }
note: if carefully, you're not passing makeresponsehandler
http.get()
, you're calling makeresponsehandler()
, passing returns http.get()
.
Comments
Post a Comment