How to create an Asynchronous callback in JavaScript really!

How to create an Asynchronous callback in JavaScript really!

Let's discuss how to put your code in the callback queue.

Hello there, This is my first blog ever. I hope you find this informative.

Recently, I've been curious about and trying to grasp the fundamentals of asynchronous operations in JavaScript. I thought it would be beneficial to share what I've learned with you.

So, to begin with, let's discuss,

Callback - When a function (f) takes a function (cb) as an argument also known as a callback function, this (cb) will run when (f) is done with all of its tasks and calls (cb) at the end.

This helps us to do Asynchronous programming, or does It? Is it not a subset of higher-order functions?

Let's take a look at the basic syntax of a callback function.

Declaration

function functionName(arg, callback) {
  let receivedArg = arg;
  callback(receivedArg);
}

Usage

functionName("Arg", function (arg) {
  console.log(arg);
});
//Output
//Arg

Boring?
Let's look at a more relatable code.

Declaration

function createUser(userData, callMeWhenDone) {
  const userSchema = {
    id: Math.floor(Math.random() * 100),
    name: userData?.name || "NA",
    email: userData?.email || "NA"
  };
  callMeWhenDone(userSchema);
}
const newUserData = {
  name: "Pradyumna Garg",
  email: "pradumnagarg@hotmail.com"
};

Usage

createUser(newUserData, (generatedUser) => {
  console.log("User Details", generatedUser);
});

console.log('Let me complete other tasks, while the user is getting generated');

Output

//"User Details" { generatedUser }
//"Let me complete other tasks, while the user is getting generated"

Here you may notice we doing synchronous operations instead of asynchronous.

Which makes this code "Meh".

So, in my opinion, the method "callMeWhenDone" should be called in such a way that it can be added to the callback queue.

So, how do we go about doing that?

SetTimeout came to mind as an easy solution, however, the callback queue is also divided into "Main task queue" and "Micro Task queue."

Although we are interested in "Micro Task queue," using setTimeout will go to "Main task queue." Hopefully, JavaScript provides a way to add a callback function inside the "Mircotask queue".

queueMicrotask(function)

So after modifying our code, it will look like this.

function createUser(userData, callMeWhenDone) {
 const userSchema = {
   id: Math.floor(Math.random() * 100),
   name: userData?.name || "NA",
   email: userData?.email || "NA"
 };
 queueMicrotask(() => callMeWhenDone(userSchema));
}

And the output would be like this.

//Output
//"Let me complete other tasks, while the user is getting generated"
//"User Details" { generatedUser }

Conclusion

In this way, we could design our own asynchronous operations to help with the development of more fruitful functions, or we could gain a better understanding of what is going on behind the scenes of code execution. I'll try to think of some more interesting topics and examples. Please provide input if you believe I can enhance it further.

Meanwhile, Have fun coding!

Did you find this article valuable?

Support Pradyumna Garg by becoming a sponsor. Any amount is appreciated!