Solving Concurrency Challenges with Asynchronous Programming
Table of contents
Hi Programmers. I hope you all are doing well. In this article, you will get to know, "What is asynchronous programming?", "What challenges have we faced without asynchronous programming?" and many more things.
INTRODUCTION
Asynchronous programming is the technique that enables our program to initiate a considerably long-running task and still be able to respond to other events while that task runs, rather than having to wait until that task is finished. Once the task is finished, we are presented with the result.
So let's deep dive into this interesting topic.
SYNCHRONOUS PROGRAMMING
Synchronous programming is the technique in which our code is executed line by line. Even if some task is potentially long-running, we will have to wait for completion of this task, for other tasks to be executed.
See the code below :
If we focus on the steps of execution,
Declaration of string named
firstName
.Declaration of another string named
lastName
.Outputs
fullName
in the console.
We should note that here the code is executed line by line, in the order it was written. At each point, the browser waits for the line to finish its work before going on to the next line.
This makes the above program a synchronous program.
Now let's see something interesting, which will explain more about synchronous programming.
Execute the above code, and you will get it.
The problem with this is, suppose we are our webpage. Our website will not be functional until these long-running tasks are executed.
Okay, I will give you a demo.
After clicking the start button, you will notice that the whole page will not be functional. You can not click anywhere. Because never-ending while the loop is running. Most probably, the page will crash. This is the problem with synchronous programming. What we need is a way for our program to:
Start a long-running operation by calling a function.
Have that function start the operation and return immediately, so that our program can still be responsive to other events.
Notify us of the result of the operation when it is eventually completed.
EVENT HANDLERS
Now, If we carefully look at the working of event handlers, we can see that they work in a manner very similar to the one discussed above. They are therefore examples of asynchronous programming. The function we pass to the event handlers is executed when a particular event occurs. The result is provided whenever the task of that function is completed.
Again, I will provide you with a demo.
Here, even if we put a long timer, we can use the functionality of the change
button. This is the power of Event Handlers.
Let us end this article here. In the next part of the article, we will discuss callbacks and the problems associated with them. How promises
to solve the problem.
Subscribe to my newsletter
Read articles from Saksham Aggarwal directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by