繁体   English   中英

javascript(node.js)| 在回调函数的范围内使用外部参数

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

我如何将id变量传递给api resquests回调函数,因为该函数只有三个固定参数?

我的意思是我不能这样做:

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

并且它不会让我添加另一个参数,导致真正的功能是

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

问候,

正在从请求模块中调用回调,您可以在回调内部使用变量id ,因为它在其外部作用域中定义,但是当您执行function(err, resp, body, id)它会创建一个新的匿名回调范围内的变量id和外部作用域中的id将无法访问。

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

或者,如果你真的想通过它,你可以做(​​虽然没用):

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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