Handling Asynchronous Operations in Node.js

Handling Asynchronous Operations in Node.js

Node.js is a JavaScript runtime built on Chrome's V8 JavaScript engine. Asynchronous operations allow Node. js to serve multiple requests efficiently. An asynchronous call is initiated, and a callback is provided that is to be called later when the results are in. Between initiating the call and firing of the callback, other computations can take place.

After a lot of digging, I understood how node.js internally works. This blog is based on my researches, stay patient to deep dive!😁

Okay! So let’s understand first what Node.js is 🐘. The documentation says: “Node.js® is a JavaScript runtime built on Chrome's V8 JavaScript engine.”

A lot of fancy words here 🤯. Let’s together break it down 💪 First thing first, what is runtime and why node.js is a runtime ???

A runtime is code/instructions executed specifically while your program is running, especially those instructions that you do not write explicitly, but are necessary for the proper execution of your code.

An engine is the actual code responsible to execute your program.It converts your code into machine code so that your computer(CPU) will execute it.

In JavaScript — The JavaScript engine translates your script into runnable machine code instructions so it can be executed by the CPU .

The JavaScript runtime environment provides your scripts with utility libraries which can be used during execution. It’s your script that references these libraries. The engine itself doesn’t depend on them.

The important thing is the JavaScript engine implementation is totally independent of the runtime environment. Engines aren’t developed with any particular environment in mind.

For example — The Chrome Browser and node.js use the same Engine — V8, but their Runtimes are different: in Chrome you have the window, DOM objects etc, while node gives you Buffers and processes.

Imagine a robot is cooking food:

  • Your code would be the instructions to the robot to cook food.
  • The engine would be the robot that can understand the instructions and act on it.
  • The runtime would be the LPG gas stove and the utensils.

Node.js is a runtime environment because it has V8 engine, libuv threadpool and OS Async Helpers. All of these gives you the power to write the JavaScript code on the server.

Coming to another fancy word: “V8 engine”🦋

The documentation says: “V8 is Google’s open source high-performance JavaScript and WebAssembly engine, written in C++.”

Well, it means, V8 is a C++ program, which receives JavaScript code, compiles, and executes it.V8’s responsibilities:

  1. Compiles and executes JS code.
  2. Handling call stack to run your JS functions in some order
  3. Managing memory allocation for objects — the memory heap
  4. Garbage collection of objects which are no longer in use
  5. Provide all the data types, operators, objects and functions
  6. Provide the event loop, but this is sometimes implemented by the browser as well

Note:-V8 dosn’t know anything about the Document Object Model (DOM) — which is provided by the browser

Let’s understand threads and processes before understanding event loop.

Anything your computer does is done using a process. For example a file is opened by a text editor process. Music is played by a music player process.

Similarly, in order to run your node program, a process is required. This process is created as soon as you run node in your terminal.

Each process has threads which actually execute the code inside the program of the process. Threads use your CPU cores to execute the code. A process can have more than one thread.

So, when you run the following code using node: const mul= 4*2; — A process is created and threads are assigned to the process to execute the code.

NodeJS process is not “single-threaded”. “Event loop” is single-threaded

Event Loop

Consider the following code:

console.log("This is the first statement");

console.log("This is the second statement");
}, 5000);
console.log("This is the third statement");


This is the first statement
This is the third statement
This is the second statement

Node.js doesn’t wait for 5 sec for the second statement, rather it executes the third statement and in parallel waits for the timer of 5 sec to expire despite of being single threaded. How? Event Loop to the rescue!

“Event loop” is, well, just a loop like a for loop or a while loop. When you start your node process by running node app.js, the following steps take place:

  1. V8 engine executes your code in app.js
  2. V8 engine immediately starts “Event Loop”

So one thing should be very much clear now — Event loop doesn’t execute your code , V8 engine is responsible or executing your code.

“Event Loop” is some piece of code in a loop which picks up tasks from“Job/Task Queue” and sends them to V8 to be executed.

Wait! Hold On! Which tasks and what is the “Job Queue”?

So a Job Queue is FIFO data-structure. The tasks which are pushed first will be picked up first by the Job Queue.

The tasks here is any code inside the function that needs to be executed. When I/O operation, setTimeout, setInterval, setImmediate, or an OS task completes, callback function is called, which is then entered inside the Job Queue.

As I mentioned above, event loop is like a for or while loop. It has certain phases through which it iterates — it is called “Event Loop Iteration”.

Each of the phases has its own queue/heap which is used by the event loop to push/store the callbacks to be executed (There is a misconception in Node.js that there is only a single global queue where the callbacks are queued for execution which is not true.).

programming javascript node web-development developer

Bootstrap 5 Complete Course with Examples

Bootstrap 5 Tutorial - Bootstrap 5 Crash Course for Beginners

Nest.JS Tutorial for Beginners

Hello Vue 3: A First Look at Vue 3 and the Composition API

Building a simple Applications with Vue 3

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

Hire Node.JS Developers | Skenix Infotech

We are providing robust Node.JS Development Services with expert Node.js Developers. Get affordable Node.JS Web Development services from Skenix Infotech.

A Guide to Web Scraping With JavaScript and Node.js

In this JavaScript Web Scraping tutorial, we’re going to illustrate how to perform web scraping with JavaScript and Node.js. Since JavaScript is excellent at manipulating the DOM (Document Object Model) inside a web browser, creating data extraction scripts in Node.js can be extremely versatile. We’ll start by demonstrating how to use the Axios and Cheerio packages to extract data from a simple website. Then, we’ll show how to use a headless browser, Puppeteer, to retrieve data from a dynamic website that loads content via JavaScript.

The Ultimate Guide to Web Scraping With JavaScript and Node.js

We’re going to illustrate how to perform web scraping with JavaScript and Node.js. Learn how to use the Axios and Cheerio packages to extract data from a simple website. Learn how to use a headless browser, Puppeteer, to retrieve data from a dynamic website that loads content via JavaScript.

Why Web Development is Important for your Business

With the rapid development in technology, the old ways to do business have changed completely. A lot more advanced and developed ways are ...

Important Reasons to Hire a Professional Web Development Company

    You name the business and I will tell you how web development can help you promote your business. If it is a startup or you seeking some...