Callback and CallbackHell in Javascript?

Callback and CallbackHell in Javascript?

Synchronous and Asynchronous Programming...

In this blog you will know about concept of callbacks and callback hell. Before understading Callback Hell and it's concpet. You should know about Synchronous and Asynchronous programming in JavaScript.

Synchronous Programming:-

  • In Synchronous programming, we perform only one task at a time, when one task is executed after that another task executes.

  • This is what we called Blocking Code operation because we need to wait for a task to finish to move to the next one.

let first= "first program"
let second= "second program"
console.log(first); 
console.log(second);
// output
//first program
//second program

In the above code snippet, you will see code execute line by line. And the output will be "first program" and "second program" simultaneously.

Asynchronous Programming:-

  • Asynchronous programming allows performing that work without blocking the main process( set of program).

  • This set of functions often related to parallelization, the art of performing independent tasks in parallel, which is achieved by using asynchronous programming.

In asynchronous operation, we can move to another task before the previous one is executed, and this way you can deal with multiple requests simultaneously.

console.log("Program Starts");
setTimeout(() => {
  console.log("Reading an user from database...");
}, 2000);
console.log("Program Ends");

Callbacks:-

Callback function is a function passed into another function as an argument, which is then invoked inside the outer function to complete some kind of routine or action.

OR

  • A callback is a function that’s passed as an argument to a second function.

  • The function which receives the callback decides if and when to execute the callback:

function myFunction(callback) {
  // 1. Do something
  // 2. Then execute the callback
  callback()
}

function myCallback() {
  // Do something else
}

myFunction(myCallback);
function myFunction(callback) {
 console.log("first")
  callback()
}

function myCallback() {
  console.log("second")
}

myFunction(myCallback);
//Output
//first
//second

Callback Hell:-

in this example you will understand the flow of callbacks:

Here it is the complete flow of user from register to displaying user data.

function register(){
  console.log("register end")
  }

function sendEmail(){
  console.log("email end") 
}

function login(){
  console.log("login end")  
}

function fetchUserData(){
  console.log("got user data") 
}

function displayUserData(){
  console.log("user data display")
}

register();
sendEmail();
login();
fetchUserData();
displayUserData();
// output:
// register end
// email end
// login end
// got user data
// user data display
  • Here we are using function but to understand (just imagine) user data is coming from API end.

  • We can assure data is coming in that flow but we can't expect the timeframe of each APIs.

  • with setTimeout function we change the time frame of each data. Then you will see the output like this.

function register(){
  setTimeout(()=> {
    console.log("register end")
  }, 1000);

}

function sendEmail(){
  setTimeout(()=> {console.log("email end")}, 2000);

}

function login(){
    setTimeout(()=> {console.log("login end")}, 3000);

}

function fetchUserData(){
    setTimeout(()=> {console.log("got user data")}, 1000); 
}

function displayUserData(){
console.log("user data display");

}

register();
sendEmail();
login();
fetchUserData();
displayUserData();

//Output:

//user data display
//register end
//got user data
//email end
//login end
  • As we can see output is not as expected. This can affect user data flow.

  • To maintain user data flow here we will use a callback.

  function waitForThreeSeconds() {
    let ms = 3000 + new Date().getTime();
    while (new Date() < ms) {}
  }

  function register(callback) {
    waitForThreeSeconds();
    setTimeout(() => {
      console.log("Register end");
      callback();
    }, 1000);
  }
  function sendEmail(callback) {
    setTimeout(() => {
      console.log("Email end");
      callback();
    }, 2000);
  }
  function login(callback) {
    setTimeout(() => {
      console.log("login end");
      callback();
    }, 3000);
  }
  function getUserData() {
    setTimeout(() => {
      console.log("Got user data");
    }, 1000);
  }
  function displayUserData() {
    console.log("user data displayed");
  }

  //callback hell
  register(function () {
    sendEmail(function () {
      login(function () {
        getUserData();
        displayUserData();
      });
    });
  });

//output
 //Register end
 //Email end
 //login end
 //user data displayed
// Got user data
  • You are seeing now a nesting of functions here and the code also looks scary.

  • This is what we called Callback Hell.

  • For a big application, it creates more nesting.

  • To resolve this issue here we use Promise in javascript.

Did you find this article valuable?

Support Sumit Singh by becoming a sponsor. Any amount is appreciated!