0

This seems to work:

function callLoop (n) {
  function caller () {
    console.log("hello from " + n);
    setTimeout(function () {
      caller();
    }, 10000);
  }

  caller();
}

for (var i = 0; i < 5; i++) {
  callLoop(i);
}

setTimeout, in this example, would instead be a long-running network call. Is this the "correct" way to parallelize these network calls?

quinn
  • 5,508
  • 10
  • 34
  • 54
  • [check out this question](http://stackoverflow.com/questions/4631774/coordinating-parallel-execution-in-node-js) – miah Aug 23 '13 at 19:56

1 Answers1

0

Check out async.parallel:

var async = require( 'async' );

function callLoop (n) {
  function caller () {
    console.log("hello from " + n);
    setTimeout(function () {
      caller();
    }, 10000);
  }

  caller();
}

var functions = [];
for (var i = 0; i < 5; i++) {
  functions.push(callLoop.bind(null, i));
}

async.parallel(functions);
fakewaffle
  • 2,981
  • 1
  • 18
  • 15
  • the example you have will terminate, whereas my example will not (this is what I want). Also, i'm not looping for the sake of an example, I actually want to execute the same code multiple times. And finally, I don't care about "synchronizing" them (i.e. waiting for them to all finish) and then doing something. – quinn Aug 23 '13 at 21:50
  • As far as "synchronizing", the last `callback` is optional. The first argument is an array of functions, which you could construct with your for loop. – fakewaffle Aug 23 '13 at 22:12
  • I updated the code. Let me know if that is what you were thinking. – fakewaffle Aug 23 '13 at 22:19