What is Asynchronous Programming?
The term asynchronous in programming means that a particular section or block of code can execute independently of other sections of code.
Asynchronous programming is generally useful to perform operations which consume a certain amount of time such as fetching data from a third party REST API or getting data from our own local database.
We can think of asynchronous code as "Starting a task now and finishing it some time later"
Synchronous vs Asynchronous
This means that it can execute only one statement at any given time, meaning that the rest of the other statements need to wait before the completion of the previous statement.
Hence synchronous code is also known as blocking code.
This is in contrast to asynchronous code where other sections of code need not wait for the asynchronous piece of code to finish execution.
Hence, Asynchronous code is also known as non-blocking code.
Synchronous Code - Illustration
console.log("Hello world!"); // Statement 1 console.log("Print some random stuff") // Statement 2 //Statement 3 - Making a network request console.log("Printing again") // Statement 4
Since Statement 3 is a network request, it will take some time to complete and assuming the synchronous model is followed here, Statement 4 has to wait for the entire network request to complete before it can execute.
Statement 3 stalls or blocks the execution of Statement 4. This is the downfall of synchronous code and hence it is known as blocking code as mentioned above. This is where asynchronous code comes into the picture.
Asynchronous Code - Illustration
Instead of the statement 3 being a synchronous function to request data, let it be an asynchronous function (we will learn how to write asynchronous functions in the upcoming posts).
Now what this means is that this function can start its execution and finish later whenever the requested data is sent back from its source.
Once the asynchronous function completes its execution, it notifies that it has completed its task through a callback function (assume it is a function which notifies completion, though we will learn about callbacks in the upcoming posts).
How does this help ?
This means that the rest of the statements can now execute without being blocked.
If you find this post helpful, please connect with me on Twitter for more such interesting content.
Thanks for checking out my post and have a happy day ahead :)
Top comments (5)
Thanks for your feedback :)
Sounds pretty clear
Nice piece !! 🤟
Thanks for your feedback. Much appreciated :). Btw this was my first article and hence was nervous whether it would be good or bad😅