为什么计数增加,closures问题

基本上我在这里要做的是,使用nmap / nodejs在7台机器上进行nmap扫描,然后当响应回滚时,我将它写入客户端页面。 当我运行这个工作正常。它使用闭包,以包装variables计数,所以每个callback得到计数= 0。

现在我不明白的是,为什么按照console.log计数值从1增加到7。 按照我的理解,每个方法都可以算。

有人可以解释为什么这是

从nodejs ::输出

server is listening 8.8.8.1 8.8.8.2 8.8.8.3 8.8.8.4 8.8.8.5 8.8.8.6 8.8.8.8 count = 1 count = 2 count = 3 count = 4 count = 5 count = 6 count = 7 ending the response 

代码::

 var http = require('http'); var cb = function(httpRequest, httpResponse){ var count = 0; var ips = []; ips.push('8.8.8.1'); ips.push('8.8.8.2'); ips.push('8.8.8.3'); ips.push('8.8.8.4'); ips.push('8.8.8.5'); ips.push('8.8.8.6'); ips.push('8.8.8.8'); var exec = require('child_process').exec; for(var i =0; i< ips.length ; i++) { exec('nmap.exe -v ' + ips[i], function(error, stdout, stderr) { if(error) { httpResponse.write(stderr); httpResponse.write("</br>") httpResponse.write("*************************"); } else { httpResponse.write(stdout); httpResponse.write("</br>") httpResponse.write("*************************"); } count = count + 1; console.log('count = ' + count); if (count === 7) { console.log('ending the response'); httpResponse.end(); } }); console.log(ips[i]); } } var server = http.createServer(cb); server.listen(8080, function(){ console.log('server is listening'); }); 

-谢谢

由于count是在代码第3行的全局空间中声明的,所以每个循环都将增加一个外部计数。 这不会导致您的计数重置。 如果你想实例化一个新的计数variables,你需要在你的循环中声明var count

count从1增加到7,因为在循环遍历包含7个元素的ips数组的循环的每个迭代中,它都会增加1 。 每个新的请求都会将计数重置为0.每个请求都会遍历所有7个元素。

看起来你想要在countvariables上使用闭包。 但是,您没有在countvariables上实现闭包。 为了将count副本传递给每个asynchronous函数,您应该将相应的代码块包装在一个函数调用中,该函数调用将count作为参数。 例如:

 var exec = require('child_process').exec; for(var i =0; i< ips.length ; i++) { (function(count) { //Start of closure function storing a local copy of count exec('nmap -v ' + ips[i], function(error, stdout, stderr) { if(error) { httpResponse.write(stderr); httpResponse.write("</br>") httpResponse.write("*************************"); } else { httpResponse.write(stdout); httpResponse.write("</br>") httpResponse.write("*************************"); } count = count + 1; console.log('count = ' + count); if (count === 7) { console.log('ending the response'); httpResponse.end(); } }); })(count); // end of closure function console.log(ips[i]); } 

运行这将得到你的输出:

 count = 1 count = 1 count = 1 count = 1 count = 1 count = 1 count = 1