What does the term Asynchronous or Synchronous means

Let's start of by understanding the meaning of both of these terms.

Consider an example where we try to print these two lines on the console.


So, this is an example of Synchronous or Blocking program. Here the second line console.log('After') will not be executed until the first line finishes it's execution. So because of line 1 , the first line will have to wait. That is why we call such code Synchronous or Blocking code.

Now, let's take example of Asynchronous or Non-Blocking program.

Now, consider this example

3// Asynchronous/Non-Blocking Function
4setTimeout(() => {
5	console.log("Reading User from the DB...");
6}, 2000);

What do you think the output will be?

2Reading User from DB...

Some of you might think that the line 1 will be executed first, then for the line 2 there will be a wait for 2 seconds and after that the line 3 will be executed. But No, this is not how the output will be. The output will be as follows :

3Reading User from DB...

Here, the setTimeout is an example of Asynchronous or Non-Blocking function, when we see this function. This function will schedule a task of executing after 2 seconds. As soon as 2 seconds gets over it will call the function we've passed in it. So, when we run the above mentioned code we will see that firstly the first line will be executed then we get to the second line and all this setTimeout function does is scheduling a task to be performed in future. It doesn't wait or block the task, it just schedules it to be performed in the future.

That is why the line 2 is printed in last and this is the difference between the Synchronous and Asynchronous code.

One thing you need to know that Asynchronous doesn't mean Concurrent or Multithreaded, In Node we have single thread and everything is handled by that single thread only.

To understand this clearly, let's take an example that a person X visited a restraunt. He asks the waiter to get himself some dish. What waiter does is that he keeps on waiting at the kitchen until the order of person X isn't prepared. The other people who are also at the restraunt will have to wait until the order of person X is served. This is an example of Synchronous. Whereas, in Asynchronous When a person X visits a restraunt and order something the waiter give him a ticket no. , assuring him that he will be served his order as soon as it gets ready. In the mean time the waiter serves the other people sitting in the restraunt not letting them to wait. So, a single waiter is serving here without letting other people to wait.