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,

2
  • you can explain better your question? Commented Nov 21, 2013 at 20:22
  • 2
    You don't have to pass it, it's defined in a higher scope and as such automatically available. Commented Nov 21, 2013 at 20:23

1 Answer 1

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);
Sign up to request clarification or add additional context in comments.

2 Comments

The first example is an example of a closure (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.
I've also posted a similar answer: stackoverflow.com/a/28120741/1695680 I feel my example may be a little more obvious to understand.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.