简体   繁体   中英

javascript (node.js) | using external params in a callback function's scope

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,

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM