DEV Community

Cover image for Dealing with asynchronous data in Javascript : Callbacks
Swastik Upadhye
Swastik Upadhye

Posted on • Updated on

Dealing with asynchronous data in Javascript : Callbacks

First of all, let us understand what is the meaning of word asynchronous in programming context.

Asynchronous

  • It is a behaviour when the program is being executed and the thread will not wait till the execution of the previous line is completed is asynchronous. ( synchronous meaning procedural one task is done then and then only another is taken)

Different ways to handle async data :

  1. Callback
  2. Promise
  3. Async-await

In this article, I am going to discuss callbacks briefly.

Consider the below example, in which user is going to make a request on server to create a student and then trying to get all students.

Normal Approach

(For the sake of simplicity, I have mimicked the server request by adding setTimeout.)

let stdList = [];
function getStudents(){
   setTimeout( () => {
    return stdList;
   },3000);
}
Enter fullscreen mode Exit fullscreen mode

In the above code snippet, the user is making a request to get the data from a server which is going to take some time ( 3 sec ) for completing it.

function createStudent(stdObj){
   setTimeout( () => {
     stdList.push(stdObj);
   },5000);
}
Enter fullscreen mode Exit fullscreen mode

In the above code snippet, the user is trying to create a student i.e writing on the server which is going to take more time ( 5 sec ) for completing it. ( Generally, this much time doesn't take in reality but for the sake of understanding I am considering this )

let stdObj = { name : "Ayush" , age : 16 , nationality : "Indian" }
createStudent(stdObj);
getStudents();
Enter fullscreen mode Exit fullscreen mode

To achieve this goal, if we go through conventional method by making one by one requests as shown in above code snippet.
After analyzing the result, the chances are very low that you will get exact output as expected.
Because write operation takes time than get operation. When we make request to the server for write operation, Javscript doesn't wait and it moves to next line and tries to execute.

So, to avoid this, callbacks plays an importantant role.
Let us understand what the heck callback is ? To understand this we need to have some basic knowledge of so called functions in Javascript ( which is the ❀️ of Javascript )


Callback (Callback Functions)

  • In JavaScript, functions are objects.
  • Functions are the first class citizens.
  • That means we can assign a function to a variable, we can return a function from a function, we can pass a function as an argument while calling a function, we can pass function as a parameter.
  • That means we can assign them to variables or can pass them to another function as a parameter.

Callback function : Function which is passed as an argument to another function and executed later on is called a Callback Function.

Higher Order Function : The function which takes another function as a parameter ( or a function that returns another function ) is called the Higher Order Function.


With Callback

function createStudent(stdObj,callback){
   setTimeout( () => {
     stdList.push(stdObj);
     callback();
   },5000);
}
Enter fullscreen mode Exit fullscreen mode
createStudent(stdObj,getStudents);
Enter fullscreen mode Exit fullscreen mode

Here, we are passing a function to another function : function getStudent is passed to the function createStudent which is totally valid in Javascript.
Now after the execution of the createStudent when we get response we are calling the getStudents ( i.e callback);
By this way, we get exact data as we expected.

Drawbacks

But wait! What if we have scenario wherein we are making multiple requests one after another. Is it feasible to go with this approach using callbacks?
The answer is big NO. Because we have to nest functions one into another which is not handy.
It is called as callback hell ( Pyramid of doom )
Moreover, it is not easy to debug the code and it's a very bad practice.
As complexity increases this can create problems.

So to overcome the drawbacks of callbacks, Promises are born.
We will see what are they and how they resolve the problems caused with callbacks in the next blog.

Thanks for reading the article, hope this will help you clear your doubts.Still if you have doubts or suggestions feel free to drop me here : LinkedIn

Top comments (4)

Collapse
 
famzil profile image
Fatima AMZIL

Super good written article (y) <3

Collapse
 
swasdev4511 profile image
Swastik Upadhye

Thanks!☺️

Collapse
 
famzil profile image
Fatima AMZIL

Waiting for your next article ^^

Thread Thread
 
swasdev4511 profile image
Swastik Upadhye

I have already published.. U cncheck it out.