1
for(var i=0;i<50;i++) {
      functionWrappingAsycfuncs(i)
}

var nums = [0,1...50]
nums.forEach(functionWrappingAsyncfuns)

functionWrappingAsycfuncs(i){
  readFileAsync(i,function(){
    console.log(i);
  });
}

In the above function , the expected nature of running it in for loop is logging of 50 50times ? But with forEach it does log 1 2 3 ....

Both these implementations look same but does really different tasks The first function calls all the async functions with 0 to 50 as params but doesn't really wait for the callbacks to complete

But the second one (in one of my projects) seems to wait for callback and proceed to next item in the array?

Are they both same?

4

1 回答 1

3

除了第二个是 50 而不是 49,它们在功能上是相同的。两者都不会在继续下一次迭代之前等待回调,并且在这两种情况下,每次调用都会捕获当前的 0...49 值作为本地参数,functionWrappingAsycfuncs因此它们都会记录 0 1 2 3...

于 2013-01-07T02:04:35.747 回答