a blog for those who code

Wednesday 25 June 2014

Nodejs : Asynchronous approach

In this post we will explain that how Nodejs asynchronously handles request. When you start a Node application, a single thread is been created, so whenever it gets a request it finish processing that request before moving it to the next request.

Now Nodejs make this processing efficient, by operating asynchronously using event loop and callback functions. An Event Loop is a functionality which handles and processes all your external events and just converts them to a callback function. It invokes all your event handlers at a proper time. So, that means while executing a single request, it does a lot of things in the back-end so that the current request or the coming request doesn't take much time.


Lets take an example of I/O operations. Nodejs event loop guarantees you that your request is never stopped or interrupted because of the expensive I/O operations. So we can say that everything runs in parallel in Nodejs except your code.

Node processes your request but it doesn't wait for the back-end process to complete before moving onto the next request. So when one request is processed  Node attaches a callback function to the request, so whenever the request is ready to be responded, an event is called which trigger the associated callback function to send the response.

Lets take an example of delivery boy who has 5 packets to deliver in 5 houses. Normally what delivery boy will do is to go to each and every house and deliver the packet. This is how Node works to process one request at a time. Problem will come when any one house is closed. Delivery boy cant stop then and there and wait till the house is opened. Then what he will do, he will call the owner and tell him that whenever the house is opened let him know as he has to deliver the packet. Till that time he will go to the next house and deliver the packet. This is what node does, it doesn't wait for the house to get open but it attaches a callback function (call from owner of house). So, whenever the request is ready to be processed (the house is opened), an event is called which trigger the associated callback function to send the response.

So, that means node doesn't process the requests in parallel but all the back-end stuffs which actually takes lot of time run in parallel. You can check the single threaded nature of node using sleep function. Since it process single request at a time you can see everything seem to be halted.

So, being a single threaded Nodejs is much faster than many threaded architectures.

No comments:

Post a Comment