Sync vs Async
Before we dig any deep, let us try and understand what do we mean by sync and async programming languages. Following example will help you understand the basic difference between the two.
Let us assume a function getUserName which calls a service and fetches the logged in user’s name.
Now, both the code appear very similar to each other. But the output for both are different.
In Java, when the function getUserName is called, the system blocks the process at line 2 and starts processing the function until the details are fetched. Once the details are fetched, it assigns the value to the variable username and then processes the next line 3. All seems to be going well here.
getUserName takes some time to fetch the data, there is no way that variable username would have any value in it until the function is processed. Hence, the output is undefined.
Because of this very basic difference between sync and async way of execution, a newbie finds themselves dealing with some of the common problems in the async world. I have tried to showcase the most common problems, along with their solutions for the same.
Code Pen: https://codepen.io/chetan1507/pen/MORKVQ
The output still remains undefined. What did we do wrong? Are you able to guess the reason?
In the previous example, we assumed that the function getUserName will execute within 1000ms and the above code works well to handle the same. In the real world, however, service call timings are not so predictable. Hence, we'll need to work out a separate solution for the same.
Let us now try and implement getUserName function in the code above using AJAX in JQuery. Try and look at the code below and see if you can find the problem.
Do you see any problem with the code above? If yes, you are already beginning to get hold of our new async world.
This is where we define what a callback function is. A callback function is a function which defines a task to be executed on the data that is being waited upon. Waiting can be caused by anything like a service call over a network or an input from the user.
In our example, a callback function would pass to the getUserName function which is fetching the data, and once fetching is complete, getUserName can defined when to use the callback function with the data. Let us look at the complete picture now with a code example.
In the example above, we don’t need to define any wait time for assigning a value and using the value from the AJAX call, as it was the case with the usage of setTimeout example. We shall talk about the callback functions in a different article with more detailed examples and use cases.
Above example has another problem, though. The variable username is global. Let's see the next example of what might go wrong with global variables.
3. The for loop and scope related problems
Consider the following code example.
Can you predict the output of the above code? See below to see if you got it right.
Seems strange? Let us try and understand what is happening here.
For the function inside setTimeout(), i is a variable in the parent scope. Now, when the setTimeout() is calling back the function after the timeout, the variable i’s value is still the same in the function scope which it was while finishing the loop, i.e., 4. Hence, when the function is called, it has access to this value and not the value that it had when it touched the setTimeout function. Hence, the output. What do we do to fix it? Pause here for a second and see what we can do to fix the above code.
Look at the following code now.
Instead of using the variable in the parent scope, we passed the value of the variable as an argument in the setTimeout method. This creates a duplicate of the variable in the local scope of the function and separates itself from the parent scope. Because we are sticking to the local scope that each of the function callbacks has of its own, we have the predicted output.
We can look more closely on the declaration of setTimeout function here. You can pass in as many objects and functions as you want in the setTimeout function.