Why thinking asynchronous is important in JS?[Part-2]
Tags: javascript
Published: 2020-12-18 21:18:25

Hello folks! Now we know the working of JS that we discussed in my last article. Let's understand how synchronous JS code can lead us to problems.

***

* Let's recall one thing - ```JS execution waits until current statement executes completely before jumping to next one```. 
* What does the above line mean? That when JS code wants to access resources outside the program, the program control waits until that block of code does its task.
* So what? What's the issue here? it's alright if we wanna access resources like files or accessing local storage(considering JS code in Nodejs).
* Yes, but the issue starts when our code hits outside our machine and goes into the network. There are chances that the URL we wanna visit doesn't exist anymore. Maybe we put wrong URL.
* In the above-mentioned cases, the main execution thread would remain blocked until the request made in network returns. This, in turn, blocks the call stack.
* What would happen now? Since the execution thread and call stack are blocked, any DOM and other events would stop resulting in the freezing of browser.
* Consider an example given below - 
```
var dummy = $.get("dummy.co.in");
var dummies = $.get("dummies.edu");

console.log(dummy);
console.log(dummies);
```
* In the snippet given above, there are chances that dummy.co.in or dummies.edu doesn't exist or maybe the server is down right now or maybe the domain has changed.

# What's the issue with the above approach?🤔

* So it's alright if we didn't get a response right?
* Yes, but the main execution thread was blocked for the whole time when program control was waiting for a response and didn't finish executing later code. 
* This is the problem that our program is waiting unnecessarily when we could've finished our remaining code and when the response came back we would've come back and printed the output.
* Therefore synchronous code would lead us to a dead-end where our main execution thread would be blocked and call stack doesn't work. 
  
# What can be done to avoid these cases?👀

* I know you guessed it right. Yes, asynchronous calls.
* Hold on! hold on! I know what are you thinking. If JS is synchronous and single-threaded how would it make asynchronous calls?
* Okay, so do you remember in the last article when we were discussing WebAPIs. I told you that they kinda provide way to write async JS.
* WebAPIs like fetch or setTimeouts() are part of the browser, not v8 but somehow v8 can communicate and access it as well as WebAPIs can access callback queue. 

```
1  console.log("1");
2  setTimeout(function timer(){
3      console.log("2");
4  }, 2000);
5  console.log("3");
6
7  // output
8  1
9  3
10 2
```
* Code snippet shows that console.log("3") being last statement executed before console.log("2").
* Because when execution started setTimeout set a timer of 2000 milliseconds inside WebAPIs section of browser. After line 2 program control jumped to line 5 logged 3 and popped the console.log("3") from the stack.
* Once timer of 2 seconds set by setTimeout stopped WebAPI pushed the callback timer() that was passed through setTimeout.
* Now timer() is queued in the callback queue. Event loop checks if stack is empty and pushes the timer() callback onto stack which in turn pushes console.log("2") onto stack.
* There we saw how console.log("2") was put on hold asynchronously but we didn't block the call stack. Call stack went ahead and put console.log("3") before the timer would have finished.

***

* Just like this, promises are also helpful to achieve async behavior.

```
   fetch("https://jsonplaceholder.typicode.com/todos")
  .then((res) => res.json())
  .then((json) => console.log(json))
  .catch((err) => console.log(err));
```
* In the above snippets, we're calling a REST api and we don't know when would it return object. So instead of blocking the main thread, we're chaining it with other methods of promise like `Promise.then()` and `Promise.catch()`.
* After an unknown time, when the response comes back. We can do whatever with it inside `Promise.then()` which is catching the promise thrown by `fetch()`.

`So never block your main execution thread and event loop`

***
*So see you in next one👋*
**Thank you if you read this long!**