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

How To Solve "Caused by: org.hibernate.HibernateException: Missing table" When Table Is Present In Database

If you are using JPA or Hibernate directly and got that exception while starting your application, there is one obvious reason for that. You...