Node.js中的asynchronoushttp.getcallback

在Node中,我有这个函数片断(大大减less了实际的function,所以希望我没有削减任何重要的东西):

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 }); } ); }; }; }; 

我所拥有的是“Driver”对象,它包含“ips”,一个包含IP地址列表的对象,例如{“192.168.1.111”:{stuff},“192.168.1.112”:{stuff}}

当然,这是我忽略的东西,但我无法按预期工作。 显然,http.get()被asynchronous调用多次。 那是我想要的; 但是,当获得结果并调用“结束”callback函数时,我无法访问“curIp”variables,该variables包含要从中调用的特定请求的原始IP地址。 相反,“curIp”variables总是包含“this.ips”中的最后一个IP地址。 我错过了什么? 任何帮助将不胜感激!

curIp没有作用于for循环,它的作用域是封闭的updateDevices函数,所以它被所有的http.get调用所共享,并且每次都通过for循环被覆盖。

解决这个问题的典型方法是创build一个立即函数,创build自己的作用域,它可以捕获每个迭代的curIp值作为该函数的参数:

 if (this.ips[curIp]) { (function(ip) { // Immediate function with its own scope http.get( { host: ip, port: 80, path: '/tstat' }, function (res) { var result = ''; res.on('data', function (chunk) { result += chunk; }); res.on('end', function () { // ip is the captured ipCur here }); } ); })(curIp); // Pass curIp into it as the ip parameter };