Introduction:
This article is aimed at providing a good understanding of how the NodeJS handles asynchronous actions using the event loop.
What is Asynchronous programming?
To explain this, I'd use the restaurant example. When you visit the restaurant and you order food, you wait while it is being prepared and while you wait for your food, the waiter attends to other customers and is not interrupted by your request(unless maybe you buy the restaurant...lol)
The illustration above gives us a good understanding of what asynchronous programming entails on a high level. NodeJS can perform this too in that it can be performing an action whilst others run in the background.
To get a good understanding of this, let's understand what synchronous code means. For synchronous code, each instruction is executed in a sequential order more like in the first-in-first-out(FIFO) pattern that is to say; if we have instruction x, instruction y, and instruction z, they will run in that order that is; x will be executed, y follows and then z. This is known as single-threading which means all instructions utilize one thread.
Also, multi-threading exists, using the illustration above, we have the instructions executed in multiple sequences which means no instruction is waiting for another to finish before it executes. This can be seen in languages like c# and Java.
NodeJS is single-threaded but it uses the event loop model which makes its operation look like a multi-threaded language.
What is the event loop?
To get a good understanding of this, let's discuss some key terms
a. Callstack: This is where the javascript engine keeps track of where it is on function execution. For example, if we have a function that sums two numbers "a" and "b".
The first thing that happens is that an anonymous function called "main()" is created on the call stack. After that, the call to execute the sum function is popped on top of the main function and then once the function finished execution, it is popped off the stack and then.
b. Node APIs: This is where events like setTimeout, setInterval, and a call to the DB are pushed. handles functions that are to be executed at a particular time.
Remember, NodeJS is single-threaded but due to the event loop model, it can perform as though it were multi-threaded. For example,
setTimeout(() => {
console.log("Hello World")
}, 5000)
The Above function is meant to run after 5 seconds. Say we have another function to execute; For example;
console.log('Yay!, I'm happy");
The call to log the string to the console will run before the setTimeout function even if the setTimeout function appears first. This normally wouldn't be the case for synchronous code but due to the event loop model, this is possible as the setTimeout is part of the Node APIs and will be pushed off the call stack (although not ended) and pushed to the Node APIs for handling. Looking at the setTimeout function, you will see that we have a callback function.
Callback in this context, simply means, what will be called at a particular time, for our case, 5 seconds. This leads us to the next important point, "The Callback Queue"
c. The Callback Queue: Maintains a list of all callback functions ready to be executed. So, after 5 seconds elapses, it will be time to log "Hello World" to our console. Firstly the function ("Callback function") is pushed to the callback queue.
The Event Loop:
This does a constant check on the call stack to see if it is free and if so, it pushes the callback function on the stack to be executed.
Recall that whilst this occurs, our function to log "Yay!, I'm happy" has already been executed.
So, when the function is now fully executed, the function along with the main function is popped off the call stack and that ends the process.
In short, if we have functions in the order shown below;
1. setTimeout(() => {
console.log("Hello World")
}, 5000)
2. console.log('Yay!, I'm happy");
The function call to log 'Yay!, I'm happy", will be displayed first before the call to log "Hello World"
Thank you for reading, hopefully, you learnt something. Honest feedbacks are also welcomed.