0

The request function (from this library). Has the following defines:

request(url, callback)

The callback argument gets 3 arguments:

  • An error when applicable (usually from http.ClientRequest object)
  • An http.IncomingMessage object
  • The third is the response body (String or Buffer, or JSON object if the json option is supplied)

So I have a function called handle response like so:

function handleRespone(error,incomingmessage,responsebody)

I'm calling it like so:

  request(url, handleRespone)

I want to add an extra parameter to the handleResponse but I'm not sure how that works. I tried it adding it request(url, handleRespone(extra)) but when I do a console.log(extra) in the handleRespone function it doesn't have the value. How do I fix this?

owenlero
  • 277
  • 1
  • 3
  • 9
  • Possible dup: http://stackoverflow.com/questions/3458553/javascript-passing-parameters-to-a-callback-function – Matej Jul 05 '14 at 17:01

2 Answers2

1

If you just define the var outside the scope of handleResponse, it will work

var extra = "panda";

function handleResponse(error, incomingmessage, responsebody) {
  console.log(extra); // "panda"
}

request(url, handleResponse);

Or, you could use an anonymous function wrapper and pass as many args as you want to your handleResponse function

request(url, function(err, incomingmessage, responsebody) {
  handleResponse(err, incomingmessage, responsebody, extra, foo, bar);
});

Otherwise, It's a little hacky (as it requires you to prepend the "extra" parameters to the beginning of your function), but you could use Function.prototype.bind

function handleResponse(extra, error, incomingmessage, responsebody) {
  console.log(extra); // "panda"
}

request(url, handleResponse.bind(null, "panda"));
Mulan
  • 129,518
  • 31
  • 228
  • 259
  • The `bind` solution is not hacky at all; it just requires modern browsers. – Noah Freitas Jul 05 '14 at 16:59
  • I only mention it as hacky because it forces him to put the `extra` variable at the beginning of the function parameters. I don't think this is a great idea. – Mulan Jul 05 '14 at 17:00
0

maybe you can try to catch your variable with the arguments object.

In your case, try

     function handleRespone(error,incomingmessage,responsebody){
             console.log(arguments[3]); 
             // your stuff ..
     }

I hope it helps you. Some information on arguments

  • the `request` function is not written with his extra variable in mind, and it's only going to pass 3 arguments. – Mulan Jul 05 '14 at 17:37