What is the benefit of async/await if only one thread is available?

Viewed 93

I am a C++ developer new to the await/async paradigm and my understanding doesn't align with my expectation what it does. Lets take a look at the following code:

fs.readFile(fileName, 'utf8', function (err, data) {
   console.log("open");
})

From my understanding, fs.readFile is asynchronous to avoid blocking. So far so good, but all tutorials mention explicetely there is only 1 thread. So how can an I/O operation be executed asynchronously, and e.g. another asynchronous function be executed if there is only 1 thread?

Let's assume (only for this example) the underlying C function open blocks for 30 seconds. Wouldn't that block the entire execution of other "asynchronous" functions as well? But that doesn't seem to be the case. So how many threads are really involved when executing asynchronous code?

My expectation would be, that it behaves like a state machine. That means, conceptually there is only 1 thread involved, but technically more than one. Is that correct?

Disclaimer: I am aware of "parallelism != concurrent".

1 Answers

I/O will run in different threads, and most I/O is non-blocking.

When people say node.js is 1 thread, it means that only 1 part of your javascript will be executed at any given time. But if you are reading a file from disk, that is slow enough that there's enough time for javascript to schedule other code to run while javascript waits for the read to complete.

Related