Callback Function in NodeJS

Kawee Lokuge
3 min readMar 31, 2018

--

Introduction

NodeJS is a javascript run time environment which runs on top of Chrome’s V8 engine.

NodeJS is single threaded and Asynchronous. CPU is in wait state most of the time in most applications. The main problem that NodeJS solves is that make use of CPU while executing the program. In synchronous programming languages like Java when a task is passed to the CPU the program waits until the result is computed and returned. But in NodeJS when a task is passed to the CPU, NodeJS doesn’t wait for the result. It just keep executing the rest of the program.

Overview

The key feature that makes NodeJS efficient is its event-driven non-blocking I/O model. But in order to handle its Asynchronous nature NodeJS make use of call back function. It is also important to remember that callbacks are not unique to NodeJS itself. Callbacks are part of vanilla JavaScript. Here we focus how callbacks are used in NodeJS. Callback is simply a JavaScript function that is passed to an asynchronous task. On completion of the task this callback function will be executed.

How Event Loop involves –

The event loop is what allows Node.js to perform non-blocking I/O operations. In Node, I/O Operations are passed to the event loop in the execution time. Event loop consists of many phases. In the IO callbacks phase of the event loop most of the callbacks are handled. Once the operation is completed the callback function executes in the main thread.

source : https://i.stack.imgur.com/cRq1h.jpg

Example -

Using Callback in a File Read.

'use strict'
const
fs = require('fs');
const fileName = 'test.txt';

fs.readFile(fileName, function(err,data){
if(err){
console.error(err);
}
console.log(data.toString());

}

);

console.log("End");

Output -

End
Hello

Here suppose that the test.txt file is in the same directory as the JavaScript file (Otherwise instead of just file name, file path should be passed to the readFile function along with the file name). test.txt file just contains text saying ‘Hello’. When the fs calls the readFile method two parameters are passed. Path to the file (file name in this case) and a callback function respectively.

In the execution path, readFile function passes its execution to the event loop which runs in the background. Then the code after the file read (Last line) is executed. (Not waiting until the file read is completed). After the file read is finished callback function gets executed. If there was an error in the file read, err captures it and prints into the console. If the file read is completed successfully data parameter captures the value and prints it.

Here we considered how callback function is used inside a readFile method. In Node different methods require callbacks which consist of different parameters. Here the names of the parameters doesn’t matter. In the example without using err and data we can use any parameter name. Only the order and the number of parameters matters. According to the order of parameters, each parameter is assigned with specific values. In this case first parameter gets error in the file read and second one gets the contents of the file that was read. But it’s important to note that it’s a good practice to use conventional parameter names.

Callback functions can be nested to handle multiple tasks. This is referred to as ‘callback hell’.

References -https://www.tutorialspoint.com/nodejs/nodejs_callbacks_concept.htm

https://nodejs.org/en/docs/guides/event-loop-timers-and-nexttick/

--

--

No responses yet