You are running a problem with the childProcess variable. JavaScript variables are a scope. Because of this, the variable is no exception to the loop.
A simplified example of code that acts as you have:
for (var i = 0; i < 3; ++i) { var someNumber = i; setTimeout(function() { console.log(someNumber); }, 100); }
outputs: 2, 2, 2
And the fix:
for (var i = 0; i < 3; ++i) { (function() { var someNumber = i; setTimeout(function() { console.log(someNumber); }, 100); })(); }
You want to wrap your logic in closure so that the childProcess variable exists with this scope. The above code displays the expected 0, 1, 2
source share