tags:

views:

157

answers:

4

How do I create a non-blocking asynchronous function? Below is what I'm trying to achieve but my program is still blocking...

var sys = require("sys");

function doSomething() {
  sys.puts("why does this block?");
  while(true);
}

setTimeout(doSomething,0);
setTimeout(doSomething,0);
setTimeout(doSomething,0);

sys.puts("main");
+1  A: 

setTimeout will not create a new thread, so the browser will still hang at the infinite loop.

You need to rethink your program structure.

KennyTM
Do you have any idea how I go about achieving this in node.js? Thanks
Richard
+4  A: 

You need to run your blocking function in a separate process.

This module can help: http://github.com/cramforce/node-worker

felixge
It's important to understand that node isn't about functions being asynchronous all the time. It's about *i/o* being asynchronous and non-blocking. If your function doesn't do any i/o, node isn't going to help you make it asynchronous. It provides tools that will allow you to do that though. Like child processes. That's what felix's answer is getting at. Your function can spawn a child process to do your work and it will execute off of the main event loop.
Marco
A: 

This line:

while(true);

isn't "blocking", it's just busy, forever.

Matt Ranney
A: 

If you don't want to use the WebWorker API / node-worker, which is still very alpha, just create an additional node program and communicate via TCP or HTTP.

This allows you to dispatch your work as HTTP calls or raw TCP data and asynchronously wait for the HTTP response / incoming TCP answer.

Note however, this is only appropriate if your task is easily serializable.

PartlyCloudy