[英]Passing loop counter as argument in Node.js
我尝试将其作为Nodeschool的教程,并且对Node.js还是陌生的。 下面的代码,我知道其中的问题,但我无法解决它。 问题在于, 对于 bl函数内部的每次循环 , j的值为3 ,但是为什么会这样呢?
var bl = require('bl');
var http = require('http');
var urls = process.argv.slice(2);
var result = [];
for (var i = 0; i < urls.length; i++) {
result.push(null);
}
for(j = 0 ; j < urls.length; ++j){
http.get(urls[j],function(response){
response.pipe(bl(function(err,data){
//console.log(result[i]);
//console.log(data.toString());
result[j] = data.toString();
console.log('J : ' + j);
console.log(data.toString());
var flag = 0;
for (var i = 0; i < result.length; i++) {
console.log('here1');
console.log(result[i]);
if(result[i] == null){
flag = 1;
console.log('here');
break;
}
}
if(flag == 0){
for (var i = 0; i < result.length; i++) {
console.log(result[i]);
}
}
}));
});
}
http.get是一个异步请求,但是for是同步的,因此for是“最快的”,当http.get完成下载url数据时,变量“ j”将取最后一个值。
我认为您还有另一个错误,在您的for循环中,将变量“ j”增加为“ ++ j”,它将是“ j ++”。
要解决第一个问题(变量“ j”的值),您可以使用匿名函数并像以下那样传递值“ j”:
for(j = 0 ; j < urls.length; j++) {
(function(j) {
http.get(urls[j],function(response){
response.pipe(bl(function(err,data){
//console.log(result[i]);
//console.log(data.toString());
result[j] = data.toString();
console.log('J : ' + j);
console.log(data.toString());
var flag = 0;
for (var i = 0; i < result.length; i++) {
console.log('here1');
console.log(result[i]);
if(result[i] == null){
flag = 1;
console.log('here');
break;
}
}
if(flag == 0){
for (var i = 0; i < result.length; i++) {
console.log(result[i]);
}
}
}));
});
}(j));
}
有很多代码,但是在简历中我这样做:
for(j = 0 ; j < urls.length; j++) {
(function(j) {
/* your code inside this function will have the correct
value to variable "j" if you use async methods */
} (j));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.