Site icon Full-Stack

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? 

Best Practices for API Design in Full-Stack Development

What is REST API with an example?

Exit mobile version