Asynchronous Programming in Node.js

What is Asynchronous ?

Asynchronous means that things which can happen independently of the main program flow.

Computers are asynchronous by design.

Current computer runs every program for a specific time slot and after that it stop executing to let another program continue executing. 

This thing runs in a cycle so fast that it is not possible to notice this process. So we think that our computer run many programs at once but this is not the case. It’s just an illusion.

This programs internally use interrupts. Interrupt is a signal emitted by a device attached to a computer or from a program within the computer.

Generally programming languages are synchronous and some use libraries to manage asynchronicity in the programming language. C, C#, PHP, Java, Python this all are synchronous by default. Some of this use threads for handle async operations.

Table of Contents

Why Node.js is asynchronous in nature ?

JS is asynchronous because it allows your code to run in the background without blocking the execution of other code so we can say that Node.js is also asynchronous in nature. Because we all know that Node.js = Runtime Environment + JavaScript Library.

Asynchronous programming is a design pattern which ensures the non-blocking code execution.

Non-blocking code don’t prevent the execution of piece of code. In general if we execute in Synchronous manner we unnecessarily stop the execution of those code which is not depended on the one you are executing.

Asynchronous does exactly opposite, asynchronous code executes without having any dependency and no order. This improves the system efficiency.

Callback hell

Asynchronous programming is great for faster execution of programs but it comes with price. That’s right, its difficult to program and most of the time we end up having callback hell scenario.

This happens due to the Asynchronous nature of the JavaScript. We want to execute tasks which are dependent on each other hence we wrap them into the callbacks of each function and hence caught into callback hell situation.

How to avoid callback hell

To avoid callback hell, follow one or combination of the following :

  • Modularise your code.
  • Use event-driven programming.
  • Use generators.
  • Use Async.js
  • Use promises

Modularise your code

The callback function is a closure and can only be accessed inside the function. However you can create separate function by providing some name and pass that function as callback.

The only drawback is you need to create lot of function as code grows.

Use event-driven programming

Node.js provides EventEmitter module that can help you to program using events. You can also use it to structure your code and avoid callback hell. However this may not help you in large structure code but it is an option.

Use generators

In simple words Generators provides you the ability to convert asynchronous code to synchronous one.

Use Async.js

Async.js is utility module provides various functions to handle the Asynchronous JavaScript.

Use promises

Promise represents the result of asynchronous function. Promises can be used to avoid chaining of callbacks. In Node.js, you can use Q or Bluebird modules to avail the feature of promise.

Callback for handle asynchronous operations

Callbacks are the traditional way of handling asynchronous operations in Node.js. They are functions that are passed as arguments to other functions, and are executed when the operation completes. For example, consider the following code:

fs.readFile(‘myfile.txt’, function (err, data) {

 if (err) throw err;

 console.log(data);

});

In this code, the fs.readFile() function is called with two arguments: the name of the file to read, and a callback function to execute when the operation completes. The callback function takes two arguments: an error object, if the operation encountered an error, and the data read from the file.

A promises is an another way to handle asynchronous operations in Node.js. A promise is an object that represents the failure of an asynchronous operation, and allows you to attach callbacks to handle the result. For example, consider the following code:

const fs = require(‘fs’).promises;

fs.readFile(‘myfile.txt’)

 .then(data => console.log(data))

 .catch(err => console.error(err));

In this code, the fs.readFile() function returns a promise, which is then used to attach a then()callback to handle the successful completion of the operation, and a catch() callback to handle any errors that may occur.

Conclusion

An asynchronous programming is a fundamental concept in Node.js, and understanding how to use callbacks, promises, and async/await functions is essential for writing efficient and maintainable code.

Like the article? Spread the word

This could be also interesting

Let's Discuss

Got a question?
We have answer!

hello@internauts.io

General Queries

Block 3 , L.D Engg Boys Hostel,
opp. Old Regional Passport office, Navrangpura, Ahmedabad,
Gujarat 380009

Ready to talk with us?

Top

© 2024 All rights are reserved

by  Internauts InfoTech LLP