例如,如果我愿意:
dict(zip(states,abbreviations))
在回调中,它将返回var request = require('request');
function callback(error, response, body) {
if (num) {
console.log(num);
}
console.log(body);
}
var cookie = {
'74358942795': 'abd7fce573c2-18c2c0de-037f-4aef-9235',
'58942743795': 'e3101e9a0e28-b596998e-e879-4003-a724'
}
function options(num) {
return {
url: 'http://.../.../',
method: 'POST',
headers: {
...
'Cookie': cookie[num]
},
body: '...=' + Date.now()
};
}
(function(num){
request(options(num), callback);
})('74358942795');
并抛出错误。
答案 0 :(得分:1)
num
不适用于callback
范围。我看到的最简单的解决方案是用以下代码替换最后一个块:
(function(num){
request(options(num), function (error, response, body){
if (num) {
console.log(num);
}
console.log(body);
});
})('74358942795');
答案 1 :(得分:1)
我不明白“forloop”与相关代码有什么关系。使用bind:
function callback(num, error, response, body) {
if (num) {
console.log(num);
}
console.log(body);
}
(function(num){
request(options(num), callback.bind(null, num));
})('74358942795');
function callback(num, error, response, body) {
if (num) {
console.log(num);
}
}
(function(num) {
setTimeout(callback.bind(null, num), 1000);
})('74358942795');
答案 2 :(得分:1)
function callback(error, response, body) {
var that = this;
if (that.num) {
console.log(that.num);
}
console.log(body);
}
(function(num){
request(options(num), callback.bind({num}));
})('74358942795');