1
回調在節點,我有這個功能片段(從實際的功能大大降低,所以希望我絲毫沒有削減任何重要的東西了):異步http.get在Node.js的
Driver.prototype.updateDevices = function() {
for (ip in this.ips) {
var curIp = ip;
if (this.ips[curIp]) { // in case this.ips[curIp] is set to undefined...
http.get(
{ host: curIp,
port: 80,
path: '/tstat'
},
function (res) {
var result = '';
res.on('data', function (chunk) {
result += chunk;
});
res.on('end', function() {
// Want to parse data for each ip, but
// curIp is always the last ip in the list
});
}
);
};
};
};
我有什麼是包含「ip」的對象,該對象包含IP地址列表,例如{「192.168.1.111」:{stuff},「192.168.1.112」:{stuff}}
Surely這是非常明顯的,我忽略了,但我無法按預期工作。顯然,http.get()被異步調用多次。這就是我想要的;但是,當獲得結果並調用「結束」回調函數時,我無法訪問「curIp」變量,該變量包含要從中回叫的特定請求的原始IP地址。相反,「curIp」變量總是包含「this.ips」中的最後一個IP地址。我錯過了什麼?任何幫助將不勝感激!
哈感謝該做的。我記得用JavaScript讀這個這個小「怪癖」,但從來沒有把它完全放在一起。謝謝 – user3321389