I'm working on a JavaScript library that provides, among other things, map/reduce functions on sequences that can be iterated asynchronously.
A helpful soul on GitHub suggested that for Node.js, I should use process.nextTick
to make asynchronous iterations as fast as possible. (The library currently uses setTimeout
in all environments, which I do understand is suboptimal.) I'm pretty inexperienced when it comes to Node, so I was reading up on how this method works and it isn't clear to me whether it's a good choice or not.
According to the answer to another question on SO, it seems that it would probably make more sense to use setImmediate
in this case as nextTick
apparently jumps ahead of pending I/O events, which seems bad to me.
This appears to be corroborated by some remarks in the official Node v0.10.0 announcment:
In v0.10,
nextTick
handlers are run right after each call from C++ into JavaScript. That means that, if your JavaScript code callsprocess.nextTick
, then the callback will fire as soon as the code runs to completion, but before going back to the event loop.
So am I right, and iterating over sequences asynchronously should be done with setImmediate
? Or would nextTick
be a better choice here? (In either case, a clear explanation why would be much appreciated.)