The Journey of an Asynchronous Call in JavaScript

The Journey of an Asynchronous Call in JavaScript

What are the different things that happen when an asynchronous call is made in JavaScript.

Synchronous operations in JavaScript

In JavaScript, when few synchronous operations are executed, each one of them needs to wait until the operation before it is completed. This means, an operation needs to wait however long the previous operation(s) takes to complete.

Asynchronous JS

But this is not the case for asynchronous operations in javascript. An asynchronous operation does not block the code following it. An asynchronous operation is executed in parallel with synchronous operations.

JavaScript is a single threaded programming language but using few smart data structures we get an illusion of multi-threading. How all this happens is very beautiful. Let's get started.

We will take a look at different data structure and constructs used for executing a javascript program.

Call stack

JavaScript has call stack which is responsible for keeping track of operations to be executed. Every operation to be executed is added to call stack. When an operation is executed it is popped from the call stack.

call_stack.png

Browser API's

Browser APIs — constructs built into the browser that sits on top of the JavaScript language and allows you to implement functionality more easily.(from MDN)

Browser has different kinds of API's built into it. When an asynchronous call is made from call stack, browser API starts it's own single threaded operation for that call.

Callback queue

Data / callback brought back by browser API is added to callback queue.

Callback queue follows queue data structure to maintain the correct sequence in which all operations should be sent for execution in call stack.

Hence we have a cyclic system for running asynchronous javascript code.

From https://www.educative.io/

Event loop

Event loop facilitates the cyclic system for asynchronous javascript code. And it checks:

  1. if call stack is empty
  2. event queue has data / callback function
  3. if 1 and 2 is true then data / callback from callback queue is added to call stack

Summary

image.png

  1. Operation calls are added to call stack. Synchronous calls are executed first.
  2. Asynchronous code is handled by browser API which brings back data / callback function.
  3. Data/ callback brought back by browser API is added to callback queue.
  4. Event Loop checks if call stack is free and if callback has items. If yes, items from callback queue is added to call stack

And that is how a beautiful circle is completed!

I hope you enjoyed this read. If you have any feedback please share in the comment below