Reputation: 109
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.
Upvotes: 4
Views: 3003
Reputation: 2490
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.
Upvotes: 3
Reputation: 55962
Exactly this only works well when the function has to be passed through an external medium. This is the tradeoff with single threaded asynchronous event loop. You should avoid any CPU bound computations in node.js because it blocks the event loop so that no callbacks can be responded to.
node only yields on OS IO calls, it does NOT yield when a callback or a promise is used. Those are two ways to handle IO based calls but are not asyncronous in themselves. (i've seen quite a few projects where people create callback based APIs for synchronous code :( )
Upvotes: 1