After using node a lot, I had to get used to writing my code in a non-blocking way, however the main way I can do this is by using functions that are themselves asynchronous. For example: stat(f,callback) or forEach(array, callback) They automatically take whatever callback you gave them out of what I would think to be the main execution highway and return immediately after being called.
What I want to know is: how can I tell the ECMA engine to execute a function asynchronously nomatter what it is?
My Particular use case involves iterating a for-loop over a DOM childList to parse the thousands of elements; my problem is that every other element is a text node which I’d like to skip over. While I would use forEach() this was not best, I only see for(a,i=0;a=table[i];i=i+2){/*process 'a'*/} being able to rectify that, at the cost of being blocking. What would be the best course of action?
Bonus Question: Does NodeJS’s coding practices hold any ground in clientside applications in use cases where JS has to do heavy lifting?
Note:
Array.prototype.forEachis synchronous, not asynchronous. Anything defined in the JS standard (ECMAScript 5th edition) cannot be asynchronous, because the standard does not define async semantics (Node.js and the DOM do).You can use
setTimeout(works in browsers and in Node.js) orprocess.nextTick(Node.js-specific):Be careful when using free variables if you choose to exploit closures, as the variables may be mutated when your callback is finally called.
With an async framework, such as Q by kriskowal (portable across Node.js and modern browsers), you can do mapreduce-style programming: