javascript - Pass extra parameter to NodeJs Http callback method -


this question has answer here:

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

Popular posts from this blog

javascript - Using jquery append to add option values into a select element not working -

Android soft keyboard reverts to default keyboard on orientation change -

Rendering JButton to get the JCheckBox behavior in a JTable by using images does not update my table -