Give sense to nonsense series: Asynchronicity in Node.js
After some weird JS behaviors, I’m changing the route and helping sail a different sea: Node.js and how it deals with async operations.
I bet that you have heard “Node.js runs on a single thread” numerous times, and I bet that for each time you heard this you thought: “Then how can operations be parallelized? I use async/await and callbacks!”.
Whenever we run a Node.js program, a thread is automatically created and our entire code is going to be executed in this single place.
Being single-threaded simplifies a lot the way you program without worrying about concurrency but you only need to pay attention to your code and avoid thread-blocking situations, such as infinite loops.
If you are a brave adventurer I suggest you explore the topic of worker threads.
Then how can asynchronicity be possible? I want to answer visually.
Take a look and this piece of code and its output:
Now some visual explanations
Image from Node.js Design Patterns — Mario Casciaro, Pack Publishing
Let’s add a new concept to this schema: Call Stack.
The call stack is a LIFO queue from which the event loop continuously checks if there’s any function that needs to run. In our specific case it would work like this:
One recurring phrase in this article is “Event Loop”
The event loop is the heart of Node.js / Javascript and it helps us deal with asynchronous operations.
Here is the visual explanation of how it works:
Picture from LogRocket blog
I hope this was helpful!