Asynchronous Javascript: Callbacks
In this Asynchronous Javascript series, I will share my knowledge about this topic with you guys.
Javascript is a single-thread programming language which means that it is not good with multi-tasking. It executes code line by line and if a function depends on the result of another function then it has to wait until other function returns the result. In this era when our computer has multiple cores, it is not a good practice to wait until some other task finish.
Handling Asynchronous operation in javascript is a very important task in javascript because every application is performing some kind of asynchronous operation and for this javascript provide different ways of handling asynchronous operation.
Callbacks
The callback is the oldest and simplest way to handle Asynchronous operation in javascript and a callback function is a function that is passed as a parameter to another function and that will execute later.
It is not necessary that a callback is always Asynchronous, it can be Synchronous too.
Example: setTimeout() function in javascript, it takes two parameters, first is a callback function and another one is the time duration, callback function, in this case, will be executed after the given time duration and until than normal flow of execution of code continue and there will be no code blocking occur.
In this example, you must be surprised by the output of the code, the reason for this output is that javascript didn’t execute the code in the order we wanted. Javascript didn’t wait for 5 seconds to execute the setTimeout() function. The reason for this behavior of javascript is that we cant call function one after another and expect that they execute in a synchronous manner. Callbacks are useful when we want to execute code after some other code execution complete.
Create a Callback
I created a fetchUser function to simulate a fetching username from the server. This function takes two arguments username and callback function and callback function defines inside setTimeout function In which we passing username as a parameter and after that, we call fetchUser function and pass the userName Parameter and invoke callback function in which we are printing username.
Callback Hell
In the above code snippet after fetching user if you want to fetch user address, then user contact, etc. For this, we have to invoke fetchAddress inside fetchUser, then for contact, we have to invoke fetchContact inside fetchAddress. This is called callback hell when we stack methods on each other and it is hard to read and not a good practice to write code.
In the next blog, I will explain to you how to handle callback hell in javascript.