【问题标题】:javascript (node.js) | using external params in a callback function's scopejavascript (node.js) |在回调函数的范围内使用外部参数
【发布时间】:2013-11-21 20:20:11
【问题描述】:

如何将 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){}

问候,

【问题讨论】:

  • 你能更好地解释你的问题吗?
  • 你不必通过它,它是在更高的范围内定义的,因此自动可用。

标签: javascript node.js parameters callback request


【解决方案1】:

正在从请求模块调用回调,您可以在回调内部使用变量id,因为它是在其外部范围中定义的,但是当您执行function(err, resp, body, id)时,它会创建一个新变量@ 987654325@ 在匿名回调范围内,外部范围的 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);

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-01-15
  • 1970-01-01
  • 2014-10-06
  • 2020-09-09
相关资源
最近更新 更多