Carlos Navarro Astiasarán Carlos Navarro Astiasarán - 11 months ago 40
Node.js Question

setTimeout to achieve asynchronicity in Node

What is the point of doing

setTimeout(fx, 0)
in node?

This is not asynchronous or even non-blocking, as the async function is really the
, not your
, and after
has run asynchronously, you will end up running
which will block your code anyway.

Doing the
to call a function
will just wait until the stack is empty to run
, but then while
is running you won't be able to accept any requests, right?

So is
setTimeout(fx, 0)
just a way of telling node 'hey, run this whenever you can'? Is there any way to trully run async functions in Node?

Answer Source

If your question is:

Can node run functions in parallel at the same time?

Then the answer is yes, but you have to use a web worker.

The paradigm of asynchronosity in node is different from traditional definitions. The expectation is that you don't run too many ultra-long running functions in node. This way, effective asynchronosity is achieved.

Node is good for some things, not for others, just like any environment.

For a more detailed answer, refer here

As for setTimeout(...,0) calls; sometimes giving a break during a time consuming task to allow calls in the queue have their share of processing can be required. Dividing tasks in different ways can save you from these; but still, this is not really a hack, it is just the way event queues work. Also, using process.nextTick for this aim is much better since when you use setTimeout, calculation and checks of the time passed will be necessary while process.nextTick is simply what we really want: "Hey task, go back to end of the queue, you have used your share!"