Node js callback function

Callback Function:- As we know node js is a asynchronous programming means whenever some task has done. This
function will call automatically, and call back function is one of the ways to have in that.

Callback features:-

Asynchronous equivalent: whenever some task has done this function will call automatically.
Non Blocking: As we know node js is a single thread, suppose so many requests are coming on the server the server will not wait for the first task to complete after that next task in node js application as soon as complete task its call back its done to perform a particular task is done.
Maintain Performance: As we know node js working on a single thread and asynchronous programming so its definitely maintenance performance.

Without Callback
In this example, the code runs step by step waiting for the complete first task.

var fs = require("fs");
console.log("First Step working");
var file = fs.readFileSync('note.txt');
console.log(file.toString());
console.log ("Task End.");

Output:

without-callback

Callback example
In this example, you can see it’s not waiting to complete the first task.

var fs = require("fs");
console.log("First Step");
fs.readFile("note.txt", function(err, file){
    if (err) return console.error(err);
    console.log(file.toString())
});
console.log("Third Step");

Output:
callback-function-output

 

Related Post

Leave a Reply

Your email address will not be published. Required fields are marked *