Search code examples
javascriptnode.jsasynchronousconcurrencyes6-promise

When to use async nodejs?


I'm not saying async of ES7, but async functions in general like callback and promisses.

So, for all I studied about NodeJS and event loop. Everything leads me to believe that NodeJS has a false sense of async.

As far as I understand this only works well when the function has to be passed through an external medium. Example, execute a read file (which will be used by the OS API), or else a request that will use the external API as well.

I found few subjects talking about it, and I would like to discuss this with you here. My questions are: Am I right with that thought? And also if there are practical ways to find out where does async work and where does it not pay? On some occasions if I am correct async will only serve to spend more memory.


Solution

  • Node.js works asynchronously, always. If you're doing some blocking I/O (such as with eg. fs.readFileSync() or other synchronous function), the complete node.js runtime process stops processing anything else during that call. Therefore, in web request processing, you never call synchronous functions (it's only acceptable in node.js command line apps and during app startup etc.)

    This is just a fundamental features of node.js; a consequence of it is that node.js/JavaScript doesn't have and doesn't need synchronized thread synchronization features like eg. Java.

    Technically, the only place in a running node.js process which is multithreaded is the internal libuv library, and only to compensate for missing asynchronous I/O of the host system.

    You can use nodes.js timers to create artificial events if your processing isn't triggered by I/O events. You're right to assume that in general, this makes nodes.js inconvenient or outright unsuitable for CPU-bound processing.