What is Synchronous vs. Asynchronous in Node.js
From this quick article, I am going to give you a basic understanding of Synchronous and Asynchronous programming in Node.js with examples that may help you to understand the concepts behind it. Let’s start!
Synchronous code is also called “blocking” as it halts the program until all the resources are available.
Synchronous execution usually uses to code executing in sequence and the program is executed line by line, one line at a time. When a function is called, the program execution waits until that function returns before continuing to the next line of code.
Asynchronous code is also known as “non-blocking”. The program continues executing and doesn’t wait for external resources (I/O) to be available.
Asynchronous execution applies to execution that doesn’t run in the sequence it appears in the code. The program doesn’t wait for the task to complete and can move on to the next task.
What Is Input/Output or I/O?
I/O is the communication between a program and the outside world such as file systems, databases, and network requests.
Sync
= Synchronous = Blocking I/O model
Async
= Asynchronous = Non-blocking I/O model
Reading From a File in Node.js With the Use of Synchronous Code
The content of the file.txt, which is the original message Hello World!
The output would be:
Reading From a File in Node.js With the Use of Asynchronous Code
Most of the time, Node.js functions are non-blocking (asynchronous) by default, and also Asynchronous functions can handle more operations while it waits for IO resources to be ready.
The output would be:
The reason for printing ‘end’ before the file output is, the program doesn’t halt and continues executing whatever is next.
Advantages of Non-Blocking Code
The illustration below compares the time taken for tasks in both synchronous and asynchronous modes.
Synchronous code wastes around 90% of CPU cycles waiting for the network or disk to get the data, but the Asynchronous code is much more performing.
Using Asynchronous code is a more efficient to have concurrency without dealing with multiple execution threads.
Hope you enjoyed my article and think this would be helpful for you to know something on Synchronous vs. Asynchronous in Node.js.
Thank You!