What is Synchronous Code?
Synchronous code is the code which executes line by line. So basically before executing the next line the previous line execution must be finished.
What is Asynchronous Code?
Asynchronous Code is the code which can execute even before the previous line is not finished executing.
So as we know JavaScript is a single threaded synchronous language. So how does async tasks like making a network call takes place in JSπππ
First let's have some examples of functions which executes asynchronously:-
- fetch()
- setTimeout()
- setInterval()
- Dom Manipulations.... and many more
So all the above mentioned functions execute asynchronously but do you know these functions are not part of the JavaScript Library. Instead they are Provided by the browserππ
More Confused... no issues let's take a look
So as we now know that these functions are not part of js library, so the questions arises where do these functions resides??
And the Answer is Web Api's
So these functions are provided by the browsers or the web api's which allows us to do async things in js.
What is Call Stack in JS?
Call Stack is a part of JavaScript Runtime and it is responsible for executing all the code line by line. It operates in LIFO manner.
How Asynchronous Code is Executed in JavaScript
Now we know some prerequisite so we can now start learning how async works in js. Due to callback functions and event loop we can perform async tasks in js.
Now what is Callback functions and Event LoopπππΆ??
CallBack Functions: are the functions which gets passed into another functions. We more dive deeper into these later...
Event Loop: So before knowing what event loop does, it is nessacery to know about some component of event loop...
- Microtask Queue
- Callback Queue
Microtask Queue: It is a queue which contain the tasks which has to be executed next. This queue has higher priority than Callback queue. This means that the tasks present here would get executed before the tasks present in Callback Queue. All the tasks which comes from Promises and Mutation Observer comes here.
Callback Queue: It is a queue which contain the tasks which has to be executed next. This queue has lower priority than microtask queue. This means that the tasks present here would get executed after the tasks present in Microtask Queue.
So finally, Event loop is just a observer or an eyekeeper, which keeps track of call stack, microtask queue and call back queue. And whenever the call stack is empty it pushes the task from the queues into call stack one by one.
So this is how we can perform Asynchronous operations in JavaScript.