1

How can i pass the id variable into the api resquests callback function as the function only has three fixed arguments?

I mean i can't do this:

 var id = 6;
    request(url, function(err, resp, body, id) {
//using here the returned body and the id too..
}

and it won't let me add another argument, cause the real function is

request(url, function(err, resp, body){}

Regards,

Egidi
  • 1,736
  • 8
  • 43
  • 69

1 Answers1

4

Call back is being invoked from the request module, you can just use the variable id as is inside the callback as it is defined in its outer scope, but the moment you do function(err, resp, body, id) it creates a new variable id inside the scope of anonymous callback and the id from the outer scope won't be accessible there.

var id = 6;
request(url, function(err, resp, body) {
     //you can access id here as is.
}

Or if you really want to pass it you can do (It is of no use though):

var id = 6;
request(url, (function(id, err, resp, body) {
     //you can access id here as is.
}).bind(this, id);
PSL
  • 123,204
  • 21
  • 253
  • 243
  • The first example is an example of a closure (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Closures). That's standard practice in JS. One thing to be careful of with it, however, is that if `id` changes before the callback function is executed then the `id` contain the new value not the original value. – Oliver Moran Nov 21 '13 at 20:28
  • I've also posted a similar answer: http://stackoverflow.com/a/28120741/1695680 I feel my example may be a little more obvious to understand. – ThorSummoner Jan 24 '15 at 00:09