## Q. ***How do Node.js works?***
<img src="assets/event-loop.png" alt="Node Architecture" width="800px" />
Node is completely event-
driven. Basically the server consists of one thread processing one event after
another.
A new request coming in is one kind of event. The server starts processing it
and when there is a blocking IO operation, it does not wait until it completes
and instead registers a callback function. The server then immediately starts
to process another event (maybe another request). When the IO operation is
finished, that is another kind of event, and the server will process it (i.e.
continue working on the request) by executing the callback as soon as it has
time.
So the server never needs to create additional threads or switch between
threads, which means it has very little overhead. If you want to make full
use of multiple hardware cores, you just start multiple instances of node.js
Node JS Platform does not follow Request/Response Multi-Threaded Stateless Model. It follows Single Threaded with Event Loop Model.
Node JS Processing model mainly based on Javascript Event based model with
Javascript callback mechanism.
**Single Threaded Event Loop Model Processing Steps:**
* Clients Send request to Web Server.
* Node JS Web Server internally maintains a Limited Thread pool to provide
services to the Client Requests.
* Node JS Web Server receives those requests and places them into a Queue.
It is known as “Event Queue”.
* Node JS Web Server internally has a Component, known as “Event Loop”.
Why it got this name is that it uses indefinite loop to receive requests
and process them.
* Event Loop uses Single Thread only. It is main heart of Node JS Platform
Processing Model.
* Even Loop checks any Client Request is placed in Event Queue. If no, then
wait for incoming requests for indefinitely.
* If yes, then pick up one Client Request from Event Queue
* Starts process that Client Request
* If that Client Request Does Not requires any Blocking IO Operations,
then process everything, prepare response and send it back to client.
* If that Client Request requires some Blocking IO Operations like
interacting with Database, File System, External Services then it will follow
different approach
* Checks Threads availability from Internal Thread Pool
* Picks up one Thread and assign this Client Request to that thread.
* That Thread is responsible for taking that request, process it,
perform Blocking IO operations, prepare response and send it back to the
Event Loop
* Event Loop in turn, sends that Response to the respective Client.
## Q. ***What is an error-first callback?***
The pattern used across all the asynchronous methods in Node.js is called
*Error-first Callback*. Here is an example:
```javascript
fs.readFile( "file.json", function ( err, data ) {
if ( err ) {
console.error( err );
}
console.log( data );
});
```
Any asynchronous method expects one of the arguments to be a callback. The
full callback argument list depends on the caller method, but the first
argument is always an error object or null. When we go for the asynchronous
method, an exception thrown during function execution cannot be detected in a
try/catch statement. The event happens after the JavaScript engine leaves the
try block.
In the preceding example, if any exception is thrown during the reading of the
file, it lands on the callback function as the first and mandatory parameter.
## Q. ***What is callback hell in Node.js?***
`Callback hell` is a phenomenon that afflicts a JavaScript developer when he
tries to execute multiple asynchronous operations one after the other.
An asynchronous function is one where some external activity must complete
before a result can be processed; it is “asynchronous” in the sense that
there is an unpredictable amount of time before a result becomes available.
Such functions require a callback function to handle errors and process the
result.
```javascript
getData(function(a){
getMoreData(a, function(b){
getMoreData(b, function(c){
getMoreData(c, function(d){
getMoreData(d, function(e){
...
});
});
});
});
});
```
**Techniques for avoiding callback hell**
1. Using Async.js
1. Using Promises
1. Using Async-Await
* **Managing callbacks using Async.js**
`Async` is a really powerful npm module for managing asynchronous nature of
JavaScript. Along with Node.js, it also works for JavaScript written for
browsers.
Async provides lots of powerful utilities to work with asynchronous processes
under different scenarios.
```
npm install --save async
```
* **ASYNC WATERFALL**
```javascript
var async = require('async');
async.waterfall([
function(callback) {
//doSomething
callback(null, paramx); //paramx will be availaible as the first
parameter to the next function
/**
The 1st parameter passed in callback.
@null or @undefined or @false control moves to the next function
in the array
if @true or @string the control is immedeatly moved
to the final callback fucntion
rest of the functions in the array
would not be executed
*/
},
function(arg1, callback) {
//doSomething else
// arg1 now equals paramx
callback(null, result);
},
function(arg1, callback) {
//do More
// arg1 now equals 'result'
callback(null, 'done');
},
function(arg1, callback) {
//even more
// arg1 now equals 'done'
callback(null, 'done');
}
], function (err, result) {
//final callback function
//finally do something when all function are done.
// result now equals 'done'
});
```
* **ASYNC SERIES**
```javascript
var async = require('async');
async.series([
function(callback){
// do some stuff ...
callback(null, 'one');
/**
The 1st parameter passed in callback.
@null or @undefined or @false control moves to the next function
in the array
if @true or @string the control is immedeatly moved
to the final callback fucntion with the value of err same as
passed over here and
rest of the functions in the array
would not be executed
*/
},
function(callback){
// do some more stuff ...
callback(null, 'two');
}
],
// optional callback
function(err, results){
// results is now equal to ['one', 'two']
});
```
* **Managing callbacks hell using promises**
Promises are alternative to callbacks while dealing with asynchronous code.
Promises return the value of the result or an error exception. The core of
the promises is the `.then()` function, which waits for the promise object
to be returned. The `.then()` function takes two optional functions as
arguments and depending on the state of the promise only one will ever be
called. The first function is called when the promise if fulfilled (A
successful result). The second function is called when the promise is
rejected.
```javascript
var outputPromise = getInputPromise().then(function (input) {
//handle success
}, function (error) {
//handle error
});
```
* **Using Async Await**
Async await makes asynchronous code look like it\’s synchronous. This has
only been possible because of the reintroduction of promises into node.js.
Async-Await only works with functions that return a promise.
```javascript
const getrandomnumber = function(){
return new Promise((resolve, reject)=>{
setTimeout(() => {
resolve(Math.floor(Math.random() * 20));
}, 1000);
});
}
const addRandomNumber = async function(){
const sum = await getrandomnumber() + await getrandomnumber();
console.log(sum);
}
addRandomNumber();
```
Post a Comment
please do not enter any spam link in the comment box