In this article I am going to talk about the concept of Asynchronous Programming.
So to begin with, I would like to first explain its counterpart, that is “Synchronous Programming”, or in lay-mans terms also known as Sequential Programming.
In Synchronous Programming the operations are carried out in a straightforward sequence that is one after the other.
To understand this concept better, consider a hypothetical program that performs the following two functions –
- Flipping a Pancake
- Spinning yourself 360 degrees
Also consider that you are the thread who will be executing this program
So if you are to execute this program Synchronously,
First you perform the Function 1 i.e. Flip The Pancake
Then after you have finished flipping the Pancake, you execute the second instruction which is ‘Spinning yourself 360 degrees’
Thus ending the program execution after the second function has been executed.
In Asynchronous Programming the operations are not carried out in the specified sequence. From the outside, it seems as if multiple things are occurring all at once!
However internally the thread uses it’s idle time to squeeze in another operation or function that is ahead in the sequence even before it has completed the function at hand.
To illustrate the working of Async Code, consider the previously mentioned functions Flipping a Pancake and Spinning 360 degrees
The following GIF represents the approach if you are to execute this program Asynchronously,
To explain the series of events this is what happens –
1. First Function 1 of Flipping the Pancake is initiated
2. While the Pancake is in the air, the thread (i.e you) have some idle time which you could utilise
3. So instead of waiting for Function 1 to complete, you execute the second function of spinning yourself
4. You catch the pancake back in the pan ending the Function1
5. And thus the program 1 comes to an end much earlier as compared to its Synchronous execution
What Next ?
Now that you have learnt how the Asynchronous Programs roll, the next thing that you should learn is to uses callbacks and promises to leverage the power of asynchronous code.
If you have enjoyed this explanation do share this article with your other developer buddies who are struggling with this concept.