2014-02-18 46 views
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地址。我錯過了什麼?任何幫助將不勝感激!

回答

2

curIp所以它是由所有http.get調用共享不作用域爲for循環,它的作用範圍是封閉updateDevices功能,並通過for每次循環將被覆蓋。

解決這個問題的典型方法是創建一個直接的功能,創建了自己的範圍,可以捕捉每個迭代的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 
}; 
+0

哈感謝該做的。我記得用JavaScript讀這個這個小「怪癖」,但從來沒有把它完全放在一起。謝謝 – user3321389