Understanding Callback

As simplest note, a callback function is a function passed into another function as an argument, which is then invoked inside the outer function to complete some kind of routine or action.

 

function greeting(name) {

alert('Hello ' + name);

}

function processUserInput(callback) {

var name = prompt('Please enter your name.');

callback(name);

}

processUserInput(greeting);


Understanding it’ s Use Case

Here is next example to readfile using callback mechanism in NodeJs to read a file.

 

var fs = require('fs');

var fcontent ;

function readingfile(callback){

fs.readFile("readme.txt", "utf8", function(err, content) {

fcontent=content;

if (err) {

return console.error(err.stack);

}

callback(content);

})

};

function mycontent() {

console.log(fcontent);

}

readingfile(mycontent);

console.log('Reading files....');


Pro Tip: Synchronous or Asynchronous Callbacks

In Synchronous Callback, code executes in blocking way. i.e. whole program is sitting still and waiting till execution of code block completes.

In Asynchronous mechanism callbacks are non-blocking i.e. does not wait around like database query, file I/O completion.

It’s not the code that is blocking/non-blocking rather the platform/environment. Nodejs is Asynchronous Platform. Platforms usually provide different types of function that executes synchronously or asynchrounously. You can choose as per your requirements.

Similarly, callback functions executed inside many modern web APIs such as fetch() where .then() block chained on the the end of a promise either on fulfilment or rejection provide Asynchronous Environment.