Async JS in a nutshell -Basics.

Some basic stuff you need to know about one of the most complex topics.

Async JS in a nutshell -Basics.

Asynchronous is one of the scariest topics for beginners but I got you. Let's begin.

What's and why's?

Well, there are a lot of definitions to understand but simply put it is something that starts now and completes after 'X' time . Do you mean, setTimeout? yes, it is an asynchronous function that executes its callback function after that 'X' time.

setTime.png

here that 'X' is 2 seconds or 2000ms. Check the output here

Why do we need it?

Javascript is synchronous by nature. That is the code executes one after the another. Line by line to be precise. For line number 100 to be executed, line no 99 should be completed/executed first in a given code block.

Take this, let us say three of us are searching Amazon for a laptop, and yeah at the same time.

So technically, Synchronous JS says that person 1 has to send a request to the Amazon server and get a response, only after that person 2s request is accepted and then he gets a response from the server. Just like we discussed earlier line by line or one after the other. And then person 3, and so forth. Think about this, a tedious process to wait and now the website is used by millions of users. So I repeat person 9999 has to wait for person 9998 to finish Damn it!.

JS Async.drawio.png

Therefore Asynchronous JS is to the rescue.

What happens in Async JS?

A little to a lot! Now, the idea is straightforward ' Start now and complete after 'X' time '. Complete what? a request, a callBack, etc. Let us start from scratch. In the earlier example of Async JS, the code snippet here, the output shockingly comes out to be. See the output in the picture below.

setTime.png

Line 1, line 2, and then line 8, line 9 is executed, and immediately callback of setTimeout is executed(not line 4, callBack is executed).

As I said setTimeout is an asynchronous function. Javascript says I saw line 1, I saw line 2 I executed them, I saw line 4 and yeah that is an asynchronous function(setTimeout) I am going to start executing it now and give back the results later because I start now and I complete/finish it after 'X' seconds. So the JavaScript 'Offloaded' that line or in sweet terms started to work on it in its backyard, went on to finish line 8 and then line 9. Once the offloaded task was done with that 'X' came back and finished it by executing that callback function.

Now you know how the scaled website deals with millions of requests and person 9999 need not wait for person 9998 because you got it it is offloaded and finished some 'X' times later. Look at the workflow below, I find it very useful.

Best JS Explanation.png

Thanks a ton for reading this and I hope you got a tiny overview. See you soon.