DEV Community

kim-jos
kim-jos

Posted on • Edited on

How is JS Asynchronous?

How does the JS engine execute code using the call stack?

Once a function is invoked and it is pushed into the call stack, the call stack executes the code immediately without waiting. So, how are asynchronous tasks possible?

How does JS perform asynchronous tasks?

Asynchronous tasks are possible in JS because of the browser(runtime environment). The browser consists of the callback queue, web api, etc. which are utilized to carry out asynchronous tasks.

Let's use setTimeout as an example. As you can see in the snapshot below setTimeout is a web API. The browser holds the function for whatever time you assigned which is 5000 milliseconds in the snapshot below. Then once the time you assigned is up the browser puts the function in the callback queue. The function waits in the callback queue until the event loops puts the function in the call stack to be executed.

image

What is the event loop?

The event loop exists to constantly monitor the callback queue and the call stack. Once the call stack is empty then the event loop pushes the first task in the callback queue into the call stack to be executed.

Let's use fetch as another example because it is also an asynchronous task but works a little differently. Fetch is also a web API that is used to request an API call. It returns a promise and we have to pass in a callback function that will be executed once the requested data is returned or the promise is resolved. Let's go over the steps on how it works.
1) It first goes to the web API to fetch data from some external server.
2) It waits in the web API environment for the requested data.
3) Once the data is returned the callback function is passed into not the callback queue but the microtask queue.

What is the microtask queue in JS?

The microtask queue serves a similar purpose as the callback queue except it has higher priority. The event loop will always check the microtask queue and carry out the functions waiting there first before it checks the callback queue.

What kind of tasks go in the microtask queue and the callback queue?

All callback functions from promises & mutation observers go into the microtask queue. Everything else goes into the callback queue.

Top comments (0)