我如何将 id 变量传递给 api resquests 回调函数,因为该函数只有三个固定参数?
我的意思是我不能这样做:
var id = 6;
request(url, function(err, resp, body, id) {
//using here the returned body and the id too..
}
它不会让我添加另一个参数,因为真正的功能是
请求(url,函数(err,resp,body){}
问候,
最佳答案
回调是从请求模块调用的,你可以只使用回调内部的变量 id
因为它是在其外部范围内定义的,但是当你执行 功能时(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);
关于javascript(node.js) |在回调函数的范围内使用外部参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20131095/