Before going to talk about asynchronous, synchronous, await & callbacks, let's go through the definition of Nodejs first
Nodejs is an open source, back-end JavaScript runtime environment & an asynchronous platform Nice !!!
Now forget the above definition of Nodejs, let's understand what is asynchronous, synchronous, await & callbacks in non-technical language ??
Suppose a boy named Rahul has to perform below 2 instructions sequentially:
- do the homework
- watch the cricket match
Synchronous: Rahul has to complete his homework if he wants to watch cricket match, means he can't go to watch cricket match until his homework wouldn't have been completed. He has to complete his 1st task before going to the 2nd one, In this system one task is performed at one time until it is completed and then move on to the next one
Asynchronous: If Rahul couldn't able to complete his homework, still he can watch the match and side by side can do his homework also. In this system multiple tasks are performed at same time. One task does not wait for other to complete it first.
So, now we understood what is asynchronous and synchronous. Cool !!!
Let's talk about await and callbacks.....but before that first let's go through the main drawback of asynchronous system.
The main drawback of asynchronous system is let's suppose the instructions which are to be performed with asynchronous style are dependent with each other, means if we have 2 instructions to perform with asynchronous style, the 1st one takes time and we moved on to the next one and performing it but what if the result of the 2nd one depends on result of 1st one?? , in that case the result of 2nd one will become inconsistent and some other problems might also arise....
Ohh what!!!
So to solve that we have to use callbacks or await
Now we have 2 options to write any code:
- Either use synchronous style
- Or use asynchronous style with await or callbacks
Using await:
Ex: let user= await User.findById(user_id);
If we are using await keyword, we have to make function asynchronous by writing async keyword before the function
By using await, we want our code to wait until it is fully completed and then we move on to the next one making the code synchronous
Using callbacks:
Ex: User.findById(user_id, (err,data)=>{});
callback= call + back (returns something after some time or at same time)
Suppose we have 2 instructions to perform with callback and they are dependent, so what we will do is we will write the 2nd instruction in the callback function of 1st one and so on..means nested callbacks
By using callbacks also, we want our code to return something so that we can know if task is fully completed or not and then we move on to the next one making the code synchronous
Now read the definition of Nodejs again !!!