Skip to main content

Command Palette

Search for a command to run...

How to create an Asynchronous callback in JavaScript really!

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

Updated
3 min read
How to create an Asynchronous callback in JavaScript really!
P

I discovered my flow state while programming.

There are people that pick someone and improve them in a number of ways so that the selected one can assist them in their growth, much like an asset. I believe I am the one who has been chosen.

It hasn't been long since I first entered the software business as a rookie developer, and I've progressed from making internal team decisions, coaching juniors, presenting new standards to the team, and finding new ways to do remarkable things.

Currently, I'm working with JavaScript and associated technologies on a professional level

  • Angular feels like home
  • React
  • NodeJs
  • TypeScript
  • I am a NoSQL guy, so "MongoDB" it is
  • Spending some time with "NextJS" as well and its interesting

Intitially for hosting and deploying web apps I started with

  • Heroku
  • Vercel
  • CleverCloud

    Then gradually shifted to AWS.

  • EC2
  • Also got know about SES, so started using it.

Recently I was introduced to Blockchain world, where I started working with

  • Hyperlegder Fabrics
  • Bash
  • Docker
  • Docker compose
  • Docker swarm

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!

G

You touched on a hidden js function, which is really knowledgeable. keep on and spread more knowledge.

1
P

Thanks for the feedback

J

Clearly written Pradyumna, minor details which you put here makes the topic more understandable...

1
P

Thanks for the valuable feedback.

H

Great

1
P

Thanks! Glad you liked it!