NodeJs Callback – Asynchronous Functions

|
| By Webner

NodeJs Callback

NodeJs is an open-source server environment and it is free. It enables javascript to run on the server-side. It runs on various platforms(Windows, Linux, Mac, etc.). Callback is asynchronous equivalent code for a function. A callback function is called when a task is completed for which it was defined. Callback gives us a way to run tasks concurrently. All APIs in Node are designed to support callbacks. Node uses an event loop to achieve asynchronous behavior.

Asynchronous functions means callback and it can be understood from the situation below:

var fs = require("fs");  // importing inbuilt file system module.
var data = fs.readFileSync('input.txt'); // reading file.

console.log(data.toString()); 
console.log("Program Ended");

In the above code, file reading is synchronous task. The statement in which we are reading file will pause the execution of the code. It will wait for the function to return the result after a complete reading of the file then the next command will run and the program will be executed.

Using callback, we can avoid this wait time like used in the below code:

var fs = require("fs"); // importing inbuilt file system 

fs.readFile('input.txt', function (err, data) { 
   if (err) return console.error(err);
   console.log(data.toString());
}); //it will pass the control to next statement and will run the callback after completion of reading task.

console.log("Program Ended");

One comment

Leave a Reply

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