Home > Articles > Web Development

Understanding Asynchronous Programming in Node.js

📄 Contents

  1. Asynchronous Programming with Node.js
  2. Using the Async Module
  3. Conclusion
  • Print
  • + Share This
Jesse Smith discusses asynchronous programming, a fundamental concept in Node.js, and shows you how it differs from synchronous programming.
Like this article? We recommend

This article discusses a fundamental concept in Node called asynchronous programming and how it differs from synchronous programming. The syntax is quite a bit different, and examples are given to show the differences between both types of programming models.

Asynchronous programming allows Node to make callback events to a single thread, thus improving performance and decreasing I/O wait time between requests. To become more effective at programming with Node, you need a good understanding of asynchronous programming and what Node offers to help you with your asynchronous code control flows.

Asynchronous Programming with Node.js

Most programmers are familiar with synchronous programming[md]writing code that does one thing after the other. For example, take the following code:

var fs = require('fs');
var content = fs.readFileSync('simpleserver1.js','utf-8');
console.log('File content: ');
console.log(content);

It writes out the code for a simple web server to the console. The code works sequentially, executing each line after the next. The next line is not executed until the previous line finishes executing. Although this works well, what if the file in this example were really large and took minutes to read from? How could other operations be executed while that code or long operation is running?

To execute operations while other long operations are running, we use function callbacks. The code below shows how to use an asynchronous callback function:

var fs = require('fs');
fs.readFile('simpleserver1.js','utf-8', function(err,data){
       if (err) {
              throw err;
       }
       console.log(“I am executed from the file finishes reading”);
       console.log('File content: ');
       console.log(data);
});

Notice that the line “I am” is executed as the file is being read, thus allowing us to perform operations while the main reading of the file is also being executed. If you are from a .NET background, this may appear similar to the using statement to perform the same kind of async calls.

You can also have callbacks within callback functions, but it often leads to a scenario referred to as spaghetti callback code. To solve the problem of run-on callbacks, Node has a module called Async to govern async callback control flow.

  • + Share This
  • 🔖 Save To Your Account