Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to assign parallel tasks in node.js

How do I make it so my server doesn't get stuck doing the 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 stuff.

    socket.on('drawing', function() {  
      for (var i = 0; i < x.length-1; i++)
      {
        //do stuff
      }  
    });
like image 270
Bob Ren Avatar asked Jun 13 '26 15:06

Bob Ren


2 Answers

Async.js has a bunch of helper functions like foreach and whilst that do exactly what you're asking for here.

Edit:

Here's a full 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!');
    }
);

Which outputs:

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

Edit 2: Changed named functions to comments to avoid confusing people.

like image 104
genericdave Avatar answered Jun 16 '26 11:06

genericdave


You can use process.nextTick to move functionality away, but it wont be truly parallel, Node.js is an event driven language so it doesn't really do threads. Here's an overview of using process.nextTick.

like image 23
Aaron Powell Avatar answered Jun 16 '26 10:06

Aaron Powell



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!