kuhaku kuhaku - 3 months ago 14
Node.js Question

About asynchronous methods and threads

What actually happens behind the scenes with asynchronous functions?

Does it open a new thread and let the OS start and run it?

If so, can it cause deadlocks or other thread problems?

Here's an example of a async method:

var fs = require('fs')
var file = process.argv[2]

fs.readFile(file, function (err, contents) {
var lines = contents.toString().split('\n').length - 1


In fs.readFile(file,callback).This is a non-blocking call which means.

  1. node's main thread stores the callback in event-table and associate it with an event which will be emitted whenever file reading process is done.
  2. By the same time node has several internal threads(thread pool) from which node's main thread assign file reading task to one of the thread.
  3. After this assignment the command is returned to main thread and main thread continues with the other tasks and file reading process is being done in background by other thread(not main thread).
  4. Whenever file reading process is completed the event associated with the callback is emitted along with the data from file and that callback is pushed into task-queue where event loop tries to push each task to the main thread(stack).
  5. And when main thread(stack) becomes available and and there is no task present before the callback's task this callback is pushed to main thread's stack by the event-loop.

Please read event-loop for more info.

So the thread which is responsible for file reading doesnt cause Deadlock to othere threads. It simply emit exception or success which is later handled by the callback