What is Synchronous vs. Asynchronous in Node.js

Ishara De Silva
Oct 27, 2020 · 3 min read
Photo by Safar Safarov on Unsplash

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.

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

Code Snippet by Author

The content of the file.txt, which is the original message Hello World!

Content of file.txt

The output would be:

The output of the above code snippet

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.

Code Snippet by Author

The output would be:

The output of the above code snippet

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!


Knowledge Sharing Program