3

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
      }  
    });

3 Answers 3

4

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

1

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.
    }
  }());  
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.