Monday, 27 July 2020

How Asynchronous Ajax Calls Get Executed In JavaScript Event Loop

I will keep this post short. There are tons of resources where you can find JavaScript and it's event loop architecture. I am here to clarify few things.
Let's take an example from this resource. It fairly explains the event loop & the event queue used by JavaScript engine. But the question is what happens when an async call is made. We know it will get pushed to event queue once the call is complete or timeout happens. But it is unclear which component does it or how it actually happens. In the resource above, that component is mentioned as "event table".
One basic thing first, Javascript engine is single threaded & the thread will run the event loop. So for example, let's talk about V8 JavaScript engine which empowers Google Chrome browser & Node.js. Now as mentioned in the resource, a setTimeout() function call will go to event table. But what does that mean?
Here is the thing. Every Javascript engine will have a host like browsers in most cases. Or in case of Node.js, it is the whole server app which is more than just V8 engine. Node.js has various C++ libraries to complement it. This host can have other threads that can handle things like doing Ajax call or setting a timer. And these threads are also capable of pushing the tasks once completed to the event queue used in JavaScript event loop.
For browsers, setTimeout() call or Ajax function call is part of Web API. For Node.js, we have C++ library like Libuv. They are outside of JavaScript engine, but can access the event queue. So even though, Javascript engine is single threaded, it can take advantage of the threads of its host.

No comments:

Post a comment

Direct Conversion From Any Number Base To Another Base Explained

Let's consider that we need to convert a base 4 number to base 8 number. Base 4 digits: 0 1 2 3 Base 8 digits: 0 1 2 3 4 5 6 7 We should...