1
votes
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?

1

1 Answers

3
votes

Aside from the second one going to 50 instead of 49, they're functionally identical. Neither will wait for a callback before continuing with the next iteration, and in both cases, each invocation captures the current 0...49 value as a local parameter to functionWrappingAsycfuncs so they'll both log 0 1 2 3...