The Node.js callback is a process or idea which reduces the burden on server, using the callback function the server can deal with incoming user requests instead of dealing with only one request, following are the concepts covered.
Callback
Working of Asynchronous code
Callback
Description
The callback are the name convention functions utilized for JavaScript functions. The main standpoint behind utilizing the callback is that when a server reading huge files it should not wait for the request to complete instead the server should deal with the next request by doing the background process and come back when the request is finished.
The callback function takes time to deliver the result instead of quick response and is utilized in input/output applications such as reading and downloading files, conversing with database.
To visualize how the callback function works in Node.js look at the example explained below.Here in the image below, the server get the request from the user and the request is processed to the database.
In this scenario, assume that the database takes around 5 minutes to deliver the response, than the server remains idle for 5 minutes until the database produce the responds and after 5 minutes user get responds result. In mean time if the second user send a request, the user has to wait until the first user request responds delivered.
To avoid such time delay process it is better to use a callback function, by using the callback the server listens to the second users request and performs the background process for the first user request, once done the responds result is delivered to the user by which the process time can be reduced. So, irrespective of how many user requests the server going to take the exact time to deliver the response.
Example
In order to know the callback function working. First, create a .js file with the following code as shown.
callback.js
[c]
console.log("User1 made a request");
setTimeout(callback,4000);
console.log("User2 made a request");
setTimeout(callback,4000);
console.log("User3 made a request");
setTimeout(callback,4000);
console.log("User4 made a request");
setTimeout(callback,4000);
function callback(){
console.log("Requested the database and deliverd the Responds in 4 seconds")
}
[/c]
Here from the code the setTimeout() function is used to delay the execution for 4 seconds and call the function and map to the database request. By compiling the above code one can get the output as shown in the image below.
Working of Asynchronous code
Description
The transmissions of asynchronous are synchronized along the transmission medium by using the special signals, for a brief understanding of asynchronous working and non-blocking code assume the flowing example.
Suppose that a train 2 is stopped outside the station because there’s a train 1 inside the stations, in order to get into the station the train 2 has to wait until the train 1 leaves the station.
Imagine if there is another track, the train 2 can happily move inside the station by taking the alternate track leaving the track were the train 1 stopped. Now, the train 1 can happily departure at its own time instead of making the other trains wait and pulled over. Similarly to how the asynchronous code works by allowing the multiple process at the same time. The figure below gives the brief explanation on asynchronous code working.
Example
The example below demonstrate the asynchronous code working, first create two .js files with the following codes.
blocking.js
[c]
var startTime = new Date().getTime();
while (new Date().getTime() < startTime + 5000);
[/c]
nonblocking.js
[c]
var http = require('http');
var url = require('url');
var cp = require('child_process');
function onRequest(request, response) {
var pathname = url.parse(request.url).pathname;
if( pathname == '/wait' ){
cp.exec('node blocking.js', Callback);
}
else{
response.writeHead(200, {'Content-Type': 'text/plain'});
response.write('SPLessons Online Tutorials\n');
response.end();
}
console.log('Established new connection');
function Callback(){
response.writeHead(200, {'Content-Type': 'text/plain'});
response.write('Thank you for waiting!\n');
response.end();
}
}
http.createServer(onRequest).listen(8080);
console.log('Node.js Server started');
[/c]
By compiling the nonblocking.js code the output can be obtained as shown in the image.
Now, run the code in browser using the localhost:8080 though which one can get the output as shown in the image below.
Now, return to the node terminal for every reload in the browser the new connection get established and can be seen in terminal as shown in the image below.
Summary
Key Points
The right use of callbacks and asynchronous codes can increase the scalability and speed of the application.
Node.js API’s support the callbacks.
The callbacks are simply known as name conventions for using the JavaScript functions.