How to assign parallel tasks in node.js

How can I make sure that my server does not get stuck in a for loop and can handle other requests? It would be nice if I could do the for loop in parallel while my server does other things.

    socket.on('drawing', function() {  
      for (var i = 0; i < x.length-1; i++)
      {
        //do stuff
      }  
    });
+3
source share
3 answers

Based on @Slace's answer, you can use asynchronous recursion.

socket.on('drawing', function {
  var i = 0;
  (function someFunction() {
    if (i < x.length - 1) {
      i++;

      // Do stuff.

      process.nextTick(someFunction)
    } else {
      // Do something else.
    }
  }());  
});
+1
source

Async.js contains a bunch of helper functions like foreach and whilst that do exactly what you ask for here.

Edit:

Here is a complete example:

async = require('async');

var i = 0

async.whilst(
    // test
    function() { return i < 5; },
    // loop
    function(callback) {
        i++;
        console.log('doing stuff.');
        process.nextTick(callback);
    },
    // done
    function (err) {
        console.log('done!');
    }
);

What outputs:

doing stuff.
doing stuff.
doing stuff.
doing stuff.
done!

Edit 2: Named functions for comments have been changed to not confuse people.

+4

process.nextTick , - , Node.js - , , . process.nextTick.

+2

All Articles