Asynchronous Functions and the Node Event Loop in Javascript

JavascriptWeb DevelopmentObject Oriented Programming

Asynchronous Functions, the programs continue to run. It does not wait! This way the waiting time of the user is reduced. Also, Javascript as a programming language itself is asynchronous.

For example, if in code we are running an expensive request, which might require a lot of time, then in case of an asynchronous function, the waiting time would be too much, and the user wouldn’t be able to perform anything else too!

Thus generally we prefer using asynchronous code when performing expensive and time-consuming operations.

Let’s take an example of Anyncronous function in javascript 

Example

console.log('One');
jQuery.get('page.html', function (data)
{
   console.log("Two");
});
console.log('Three');

Output

One, Two, Three

Now, let’s see what is an event loop in Node.

The event loop is created inside a thread schedule in which operations our thread should be performing at any given point in time.

Any Node.js application comprises of callbacks that are executed in reaction to various events such as an incoming connection, I/O completion, timeout expiry, Promise resolution, etc. The main thread (which we now know is the Event Loop) executes all these callbacks.

When the Event loops are running, for every iteration Node checks if it is waiting for any asynchronous I/O or timers. And if nothing is found, the node shuts them down.

raja
Published on 06-Aug-2020 07:54:26
Advertisements