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
}
});
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With