top

Asynchronous Nature of JavaScript

Javascript is the fourth most commonly searched programming language and is increasingly becoming the most adopted language in web and mobile applications world. It can be hard for a newbie to get their feet wet in JavaScript, especially for the ones who started off programming with sync languages like Java, C or C++. Let us try and understand the common problems that are faced while working with javascript for the first time. 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. Java Code: String username; username = getUserName(); System.out.println(username); //output: John Doe Javascript Code: var username; username = getUserName(); console.log(username); //output: undefined 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. In Javascript, though, that is not the case. When line 2 is executed in javascript, the system doesn’t block the call stack until the function getUserName is completely executed. Instead, it goes on and processes the next line 3 due to its async behavior. Now, assuming that 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. 1.Sleep function Let’s try and fix the javascript code above by adding a typical sleep() or wait() call, and assuming that it takes 1000 ms for the function getUser() to fetch the data. Javascript Code: See the Pen <a data-cke-saved-href='https://codepen.io/chetan1507/pen/MORKVQ/' href='https://codepen.io/chetan1507/pen/MORKVQ/'>Javascript Async Nature - Sleep - Ex - 1</a> by chetan agrawal (<a data-cke-saved-href='https://codepen.io/chetan1507' href='https://codepen.io/chetan1507'>@chetan1507</a>) on <a data-cke-saved-href='https://codepen.io' href='https://codepen.io'>CodePen</a>. The output still remains undefined. What did we do wrong? Are you able to guess the reason? If you look closely, we did nothing different by adding the sleep function. It was as similar to the getUser function. In javascript, if we want to wait for a function to finish its execution for some time, we have a predefined inbuilt function setTimeout. Here is how we can fix the above code. Javascript Code: See the Pen <a data-cke-saved-href='https://codepen.io/chetan1507/pen/BmEjGp/' href='https://codepen.io/chetan1507/pen/BmEjGp/'>Javascript Async Nature: Sleep: Ex-2</a> by chetan agrawal (<a data-cke-saved-href='https://codepen.io/chetan1507' href='https://codepen.io/chetan1507'>@chetan1507</a>) on <a data-cke-saved-href='https://codepen.io' href='https://codepen.io'>CodePen</a>. In the code above, setTimeout calls the function which executes the console statement on line 4 after 3000ms is passed. We will understand the in-depth working of the above code when we are learning about Javascript Call Stack. For now, we can skip the internal working of the setTimeout function and assume it to be an alternative for sleep function in our async world. 2. AJAX 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. Javascript Code: See the Pen <a data-cke-saved-href='https://codepen.io/chetan1507/pen/NwmNYB/' href='https://codepen.io/chetan1507/pen/NwmNYB/'>Javascript Async Nature: AJAX: Ex-1</a> by chetan agrawal (<a data-cke-saved-href='https://codepen.io/chetan1507' href='https://codepen.io/chetan1507'>@chetan1507</a>) on <a data-cke-saved-href='https://codepen.io' href='https://codepen.io'>CodePen</a>. Do you see any problem with the code above? If yes, you are already beginning to get hold of our new async world. In the code above, we make a JQuery based AJAX call to the server. In Java, the code on line 3 would have waited for the $.get to finish execution and then pass on the value to user_name in line 4, which again would have been returned in line 6. But since it’s Javascript, it’s not going to wait for the lines 3-5 and move to line 6 directly after line 3 is processed, where it would return an undefined value, like in our first code snippet. 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. Javascript Code: See the Pen <a data-cke-saved-href='https://codepen.io/chetan1507/pen/eeoZxY/' href='https://codepen.io/chetan1507/pen/eeoZxY/'>Javascript Async Nature: AJAX: Ex-2</a> by chetan agrawal (<a data-cke-saved-href='https://codepen.io/chetan1507' href='https://codepen.io/chetan1507'>@chetan1507</a>) on <a data-cke-saved-href='https://codepen.io' href='https://codepen.io'>CodePen</a>. 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. Javascript Code: See the Pen <a data-cke-saved-href='https://codepen.io/chetan1507/pen/EbJyNZ/' href='https://codepen.io/chetan1507/pen/EbJyNZ/'>Javascript Async Nature: For Loop: Ex-1</a> by chetan agrawal (<a data-cke-saved-href='https://codepen.io/chetan1507' href='https://codepen.io/chetan1507'>@chetan1507</a>) on <a data-cke-saved-href='https://codepen.io' href='https://codepen.io'>CodePen</a>. Can you predict the output of the above code? See below to see if you got it right. //console output 4 second(s) elapsed 4 second(s) elapsed 4 second(s) elapsed 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. Javascript Code: See the Pen <a data-cke-saved-href='https://codepen.io/chetan1507/pen/QOPEGe/' href='https://codepen.io/chetan1507/pen/QOPEGe/'>Javascript Async Nature: For Loop: Ex-2</a> by chetan agrawal (<a data-cke-saved-href='https://codepen.io/chetan1507' href='https://codepen.io/chetan1507'>@chetan1507</a>) on <a data-cke-saved-href='https://codepen.io' href='https://codepen.io'>CodePen</a>. 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. //console output 1 second(s) elapsed 2 second(s) elapsed 3 second(s) elapsed 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. If you faced any of these challenges while working with Javascript and if this article helped you, please share this with your friends. If there are any other challenges that you face more often than the ones mentioned here, would love to hear your thoughts. I'll try my best to address them and put it here.  
Rated 4.0/5 based on 20 customer reviews
Normal Mode Dark Mode

Asynchronous Nature of JavaScript

Chetan Agrawal
Blog
08th Dec, 2017
Asynchronous Nature of JavaScript

Javascript is the fourth most commonly searched programming language and is increasingly becoming the most adopted language in web and mobile applications world. It can be hard for a newbie to get their feet wet in JavaScript, especially for the ones who started off programming with sync languages like Java, C or C++. Let us try and understand the common problems that are faced while working with javascript for the first time.

Sync vs Async

asynchronous and synchronous

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.

Java Code:

String username;
username = getUserName();
System.out.println(username);
//output: John Doe

Javascript Code:

var username;
username = getUserName();
console.log(username);
//output: undefined

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.

In Javascript, though, that is not the case. When line 2 is executed in javascript, the system doesn’t block the call stack until the function getUserName is completely executed. Instead, it goes on and processes the next line 3 due to its async behavior. Now, assuming that

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.

1.Sleep function

Let’s try and fix the javascript code above by adding a typical sleep() or wait() call, and assuming that it takes 1000 ms for the function getUser() to fetch the data.

Javascript Code:

The output still remains undefined. What did we do wrong? Are you able to guess the reason?

If you look closely, we did nothing different by adding the sleep function. It was as similar to the getUser function. In javascript, if we want to wait for a function to finish its execution for some time, we have a predefined inbuilt function setTimeout. Here is how we can fix the above code.

Javascript Code:

In the code above, setTimeout calls the function which executes the console statement on line 4 after 3000ms is passed. We will understand the in-depth working of the above code when we are learning about Javascript Call Stack. For now, we can skip the internal working of the setTimeout function and assume it to be an alternative for sleep function in our async world.

2. AJAX

ajax

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.

Javascript Code:

Do you see any problem with the code above? If yes, you are already beginning to get hold of our new async world.

In the code above, we make a JQuery based AJAX call to the server. In Java, the code on line 3 would have waited for the $.get to finish execution and then pass on the value to user_name in line 4, which again would have been returned in line 6. But since it’s Javascript, it’s not going to wait for the lines 3-5 and move to line 6 directly after line 3 is processed, where it would return an undefined value, like in our first code snippet.

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.

Javascript Code:

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.

Javascript Code:

Can you predict the output of the above code? See below to see if you got it right.

//console output
4 second(s) elapsed
4 second(s) elapsed
4 second(s) elapsed

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.

Javascript Code:

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.

//console output
1 second(s) elapsed
2 second(s) elapsed
3 second(s) elapsed

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.

If you faced any of these challenges while working with Javascript and if this article helped you, please share this with your friends. If there are any other challenges that you face more often than the ones mentioned here, would love to hear your thoughts. I'll try my best to address them and put it here.

 
Chetan

Chetan Agrawal

Blog Author

Chetan Agrawal is a co-founder and product head at Sportzify, a startup in sports segment. Prior to this, he was working as a full stack developer at Amazon and CK-12 Foundation. He loves tinkering around with Javascript Frameworks, Express.js and React.js being his favorite.


Website : http://www.chetan1507.in/

Leave a Reply

Your email address will not be published. Required fields are marked *

SUBSCRIBE OUR BLOG

Follow Us On

Share on

other Blogs

20% Discount