Understanding Callbacks in Node.js: A Beginner’s Guide

What is Callback?

In Node.js, a callback is the asynchronous counterpart of a function. This kind of function is unique in that it can be supplied as an argument to another function. Callbacks are heavily used in Node.js. We can make asynchronous calls with the aid of callbacks. The design of every Node.js API ensures that callbacks are supported.

By default, programming instructions are carried out synchronously. The main thread of execution is halted when a program’s instructions are intended to carry out a time-consuming operation. Only after the present I/O is finished may the next instructions be carried out. Callbacks enter the picture at this point.

When the function that takes the callback as an argument finishes running, the callback is called, allowing the callback’s code to continue running in the interim. Because it can handle a large volume of requests without waiting for any function to produce results, Node.js is extremely scalable.

The following is the syntax for implementing callback in Node.js:

callback body } functionfunction_name(argument,function(callback_argument){//

In Node.js, the setTimeout() method is a common callback example. The code that follows invokes the asynchronous setTimeout() method, which does not halt the thread but waits for 1000 milliseconds. Rather, the timed message came after the Hello World greeting.

Example

Open Compiler

setTimeout(function(){ 
   console.log('This prints after 1000 ms');},1000);

console.log("Hello World");

Output

Hello World
This prints after 1000 ms

Blocking Code Example

To understand the callback feature, save the following text as input.txt file.

The following code reads the file synchronously with the help of readFileSync() function in fs module. Since the operation is synchronous, it blocks the execution of the rest of the code.

var fs =require("fs");var data = fs.readFileSync('input.txt');

console.log(data.toString());let i =1;while(i <=5){
  console.log("The number is "+ i);
  i++;}

The output shows that Node.js reads the file, displays its contents. Only after this, the following loop that prints numbers 1 to 5 is executed.


The number is 1
The number is 2
The number is 3
The number is 4
The number is 5

Non-Blocking Code Example

The following code illustrates the use of callback using the same input.txt file.

The fs module’s ReadFile() function has a callback function. Error and the ReadFile() function’s return value are the two parameters supplied to the callback. When ReadFile() returns either error or the contents of the file, the callback is triggered. Node.js executes the following loop asynchronously while the file read operation is inprocess.

var fs =require("fs");
fs.readFile('input.txt',function(err, data){if(err)return console.error(err);
   console.log(data.toString());});let i =1;while(i <=5){
  console.log("The number is "+ i);
  i++;}

Output

The number is 1
The number is 2
The number is 3
The number is 4
The number is 5

Callback as Arrow function

An arrow function can also be passed as a callback argument. In JavaScript, the arrow function is an anonymous function. Another name for it is the lambda function. The following is the syntax for utilizing the arrow function as a Node.js callback:

function name(argument,(call)

lback_argument)=>{// callback body })

It was introduced in ES6 version of JavaScript. Let us replace the callback in the above example with an arrow function.

var fs =require("fs");

fs.readFile('input.txt',(err, data)=>{if(err)return console.error(err);
   console.log(data.toString());});let i =1;while(i <=5){
  console.log("The number is "+ i);
  i++;}

The above code produces a similar output as the previous example.

It might be helpful:

What’s New in Node.js 21/22? 

MERN vs MEAN vs PERN: Which Stack is Best for Your Career?

What is REST API with an example?

Error: Contact form not found.

₹25,000.00

SAP SD S4 HANA

SAP SD (Sales and Distribution) is a module in the SAP ERP (Enterprise Resource Planning) system that handles all aspects of sales and distribution processes. S4 HANA is the latest version of SAP’s ERP suite, built on the SAP HANA in-memory database platform. It provides real-time data processing capabilities, improved…
₹25,000.00

SAP HR HCM

SAP Human Capital Management (SAP HCM)  is an important module in SAP. It is also known as SAP Human Resource Management System (SAP HRMS) or SAP Human Resource (HR). SAP HR software allows you to automate record-keeping processes. It is an ideal framework for the HR department to take advantage…
₹25,000.00

Salesforce Administrator Training

I am text block. Click edit button to change this text. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut elit tellus, luctus nec ullamcorper mattis, pulvinar dapibus leo.
₹25,000.00

Salesforce Developer Training

Salesforce Developer Training Overview Salesforce Developer training advances your skills and knowledge in building custom applications on the Salesforce platform using the programming capabilities of Apex code and the Visualforce UI framework. It covers all the fundamentals of application development through real-time projects and utilizes cases to help you clear…
₹25,000.00

SAP EWM

SAP EWM stands for Extended Warehouse Management. It is a best-of-breed WMS Warehouse Management System product offered by SAP. It was first released in 2007 as a part of SAP SCM meaning Supply Chain Management suite, but in subsequent releases, it was offered as a stand-alone product. The latest version…
₹25,000.00

Oracle PL-SQL Training Program

Oracle PL-SQL is actually the number one database. The demand in market is growing equally with the value of the database. It has become necessary for the Oracle PL-SQL certification to get the right job. eLearning Solutions is one of the renowned institutes for Oracle PL-SQL in Pune. We believe…
₹25,000.00

Pega Training Courses in Pune- Get Certified Now

Course details for Pega Training in Pune Elearning solution is the best PEGA training institute in Pune. PEGA is one of the Business Process Management tool (BPM), its development is based on Java and OOP concepts. The PAGA technology is mainly used to improve business purposes and cost reduction. PEGA…
₹27,000.00

SAP PP (Production Planning) Training Institute

SAP PP Training Institute in Pune SAP PP training (Production Planning) is one of the largest functional modules in SAP. This module mainly deals with the production process like capacity planning, Master production scheduling, Material requirement planning shop floor, etc. The PP module of SAP takes care of the Master…
X
WhatsApp WhatsApp us
Call Now Button