About me

I am a full stack .net developer with 5 years of experience in front-end and back-end technologies like HTML, CSS, Jquery, Angular, Typescript, Bootstrap, C#, MSSQL and Mongodb. I have done bachelor's in computer engineering from Gujarat Technological University. I have worked on web applications, Web APIs, Windows Forms, Web Forms, Tray applications and corporate websites. Programming is my hobby and I have starting writing blog to provide a platform for those who want to grow their career as a fullstack .NET developers.

Click here to know more about me

Asynchronicity & Callbacks in JavaScript

Asynchronicity in JavaScript

Well, a simple JavaScript code will look something like the below example:

document.write("Start code"); //Prints string "Start code"

function name() {

  return "Soumya Panicker";

}

document.write("<br/>" + name()); //Prints the string returned from the function name()

document.write("<br/>End code"); //Prints the string "End code"

In this program, the first line prints the string "Start code". After that, I have defined a function called name which returns my name. I have created this function to simulate the scenario where data comes from some external source (like a server or any API or something like that). The next line prints the name returned from the function call and the last line prints the string "End code".

On running this code on the web console, we get the output as shown in the below image:

JavaScript Code and the Output from the web console
Synchronous JavaScript Code example and the Output in the web console

This was something straightforward right? This is a synchronous JavaScript program that executes and gives the output in a sequence.

Let's convert this synchronous code into asynchronous code

Asynchronous code means the code snippet that does not execute in a sequence as it is written due to some delay that we put intentionally or due to the time taken to get data from the external sources (Example: AJAX call). AJAX is used to fetch data from the server or any external API. Don't worry much about AJAX as of now. We will cover it in further lessons.

I am going to put an intentional delay of 1 sec in the above example that we saw as shown in the below code:

document.write("Start code");

function name() {

  setTimeout(function() {

    return "Soumya Panicker";

  }, 1000);

}

document.write("<br/>" + name());

document.write("<br/>End code");

In this example, I have added a timeout of 1000ms in the name() function. The output would be as shown in the below image:

Asynchoronous JavaScript code in the web console with the output
Asynchronous JavaScript code in the web console with the output

As you can see in the output, we will get undefined because of the timeout that we have added as the function returns the value after 1s it is being called. This is the asynchronicity of the code. 

Will Callback functions help us to access the value?

The answer to this question is yes, we can get the value displayed using the callback function.

What is a callback function?

💡 A callback function is a function passed as a parameter to another function inside which it is called. Sounds strange?

USE CASE OF CALLBACK FUNCTION: Used when we want to access some values from one function to multiple functions

In our example, we are getting "undefined" value returned while calling the name() function due to the timeout. Instead of returning the value, I can print the value directly over there, right? But what if we need this value for any other function to execute this code? All we can do is to pass this string to another function as shown in the below code:

document.write("Start code");

function name() {

  setTimeout(function() {

    displayName("Soumya Panicker");

  }, 1000);

}

function displayName(str){

document.write("<br/>" + str);

}

name();

document.write("<br/>End code");

From this code, we will be able to access the string and print it with the help of displayName() method. The output for this would be as shown below:

Example code and the output in web console
Example code and the output in web console

Now, consider that we have another common function that prints "welcome " + name as shown below:

function displayWelcomeMsg(str) {

  document.write("Welcome " + str);

}

Is it good to keep calling all the functions inside the timeout function, one after another? No, for that we can pass a parameter to name() to which we can pass the value as a function call as shown below:

function name(callbackFun) {

  setTimeout(function() {

    callbackFun("Soumya Panicker");

  }, 1000);

}

Now, we can directly pass the function that needs to be called as a parameter to the name() as shown below:

name(displayName);

name(displayWelcomeMsg);

The final code and the output would be as shown in the below image:

Callback example and output in the web console
Callback example and output in the web console

Thus, asynchronicity is something that changes the sequence of execution of the code due to some delay, and callback functions are used to make the function call dynamic as we did in the above example. The callback function can be used with both synchronous and asynchronous code.

I hope this article is useful to understand asynchronicity and callback functions. For any queries, you can write to me at [email protected]. To get notified for the releases, subscribe through email. If you found this article useful, please share it. Thank you 😊.