Nodejs: Callback function and its concept

Nodejs has become widely popular due to its core factor “Asynchronism”. A callback is an asynchronous functional paradigm that often refers to be as “Higher-order function”. In Nodejs, most of the functions work as callback variants.

When an argument(callback function) in Nodejs is passed to another function, only the function definition is passed. This calling function mechanism is solely responsible for the timing of callback function execution. This is the sole basis of the asynchronous behavior of the Nodejs framework.

A callback function is a function which is:

  • Accessible by another function, and
  • It starts after the first function gets complete.

These functions in JavaScript will always pass as arguments to other functions. A callback function is called with arguments containing information that relates to the tasks:

  • data object
  • result object, and
  • error object

Node uses callback functions heavily so all the APIs of Nodejs are created in such a way to support callbacks.

For example, If a file I/O is complete, it will call the callback function while passing the callback function. And the remaining content of the file as a parameter. So there is no wait for File I/O. Such an execution property called non-blocking makes Nodejs highly scalable.

Thus, enabling it to process a high number of requests without waiting for any function to return results.

BLOCKING FUNCTION

NODEJS NESTED CALLBACK FUNCTION

NODEJS NESTED CALLBACK FUNCTION
NODEJS NESTED CALLBACK FUNCTION

Nodejs nested callback function is a JavaScript function where it can be nested within other functions. A nested function or inner function can access the arguments and variables of an outer function where it is nested within. You can nest the callback function if any need for multiple operations to be done asynchronously.

EXAMPLES: NodeJS FUNCTIONS

  • Blocking Function
  • Callback Function
  • Nested Callback Function

BLOCKING FUNCTION

EXAMPLE:

read-file-sync.jsvar fs = require('fs'); // read file sample.txtVar data = fs.readFilesync(‘sample.txt’)console.log("Reading file completed : " + new Date().toISOString()); console.log("After readFileSync statement : " + new Date().toISOString());

When the above program runs, the terminal output will be as follows:

Terminal output

hari@hari - VPHAS26A:~/ nodejs$ node read-file-async.jsReading file completed : 2020-02-03t1.13:52.103zAfter readFilesync statement : 2020-02-03t1.13:52.105z

In the above example, fs.readFileSync is blocking the execution flow. After readFileSync statement is executed only after reading the file is completed.

NODEJS CALLBACK FUNCTION

EXAMPLE:

read-file-sync.jsvar fs = require('fs'); // read file sample.txtfs.readFile (‘sample.txt’,// callback function that is called when the reading file is done function(err, data) { if (err) throw err;        // data is a buffer containing file content        console.log("Reading file completed : " + new Date().toISOString());}); console.log("After readFile asynchronously : " + new Date().toISOString());

When the above program runs, the terminal output will be as follows:

Terminal output

hari@hari - VPHAS26A:~/ nodejs$ node read-file-async.jsafter readFile  asynchronously : 2020-02-03t1.13:52.987zreading file completed : 2020-02-03t1.13:52.992z

You may observe that even after executing console.log, it has not blocked the execution. Instead, a new process is started in parallel with the main control flow, to read the file (perform the task on the resource).

NODEJS NESTED CALLBACK FUNCTION

EXAMPLE:

nodejs-nested-callback.jsvar fs = require('fs'); fs.rename('sample.txt', 'sample_old.txt',    // 1st call back function    function (err) {        if (err) throw err;        console.log('File Renamed.');        fs.unlink('sample_old.txt',            // 2nd call back function            function (err) {                if (err) throw err;                console.log('File Deleted.');            }        );     });

When the above program runs with the node, the output will be as follows:

Terminal output

hari@hari-VPHAS26A:~/nodejs$ node nodejs-nested-callback.jsFile Renamed.File Deleted.

In this blog, we have learned the basics of Nodejs callback functions by covering the following topics,

  • Execution flow of Callback functions with example.
  • How they are non-blocking with example.
  • How to use nested callback functions with example.

FINAL WORDS

If you still have any queries regarding the about Nodejs and it’s developmental ideas, please feel free to Contact us for zero-cost consultation today.

Ecommerce consultant