Node.js depend on the asynchronous code to do the execution fast so having dependable callbacks is very crucial. Callback functions is called at the completion of any task. In node, code is dependent on callback, so that every thing execute fast.
Lets create an example of callback in which we understand the concept more clearly.
Create a file example.txt file and write the below text in it and save it.
'Learning callback in node.js.'
Create another file main.js and write below code in it and save the file.
var fs = require("fs");
// Asynchronous read from the file
fs.readFile('example.txt', function (err, data) {
if (err) {
return console.error(err);
}
console.log("Asynchronous read: " + data.toString());
});
// Synchronous read from the file
var data = fs.readFileSync('example.txt');
console.log("Synchronous read: " + data.toString());
console.log("Program Ended of reading from the file");
When you run the main.js file the output will be like:
kedar@kedar:/var/www/html/node_express/dummy$ nodejs filemain.js
Synchronous read: 'Learning callback in node.js.'
Program Ended of reading from the file
Asynchronous read: 'Learning callback in node.js.'
kedar@kedar:/var/www/html/node_express/dummy$
This clearly explaining that if the reading of the file taking time then because of asynchronous read of file the deadlock situation doesn't came, it switches to another line of code and start doing that and take the asynchronous one in background and printed it later on.
Asynchronous callbacks can be also called as non-blocking code as it doesn't block the code from further execution while synchronous can be called as blocking code as it doesn't allow the code from further execution until the current task is done.
0 Comment(s)