Introduction to callbacks in Node.js

If you are familiar with JavaScript, you may have got acquainted with the concept of callbacks. If not, no worries, as here we will be discussing some basics of callbacks and how they actually work with respect to node.js.

You may already know that the type of JavaScript functions is Object. So, just like any other object such as Array or String, we can pass functions as arguments to any other function while calling it.

Knowing this, we can say that callback is a function that you pass as a parameter to another function. Callbacks are a great way to handle your code when a particular piece of code has been executed. If we want to execute a function right after the return of some other function, then callbacks can be used. Let’s try to understand the same with the help of an example.

const callback = (sum) => console.log("The sum is: "+sum);

In the above code, we have defined a callback, which we will pass as an argument to our getSum() method.

function getSum(num1, num2, callback) {
callback(num1+num2);
}

Now, let’s make a call to getSum() with our callback method.

getSum(4,5,callback);

Here we are passing a callback as a third argument to the getSum() method. The output to the above method call will be

The sum is: 9

In node.js, we basically use callbacks for handling asynchronous operations like – making any I/O request, database operations or calling an API to fetch some data. Callback allows our code to not get blocked when a process is taking a long time. Let’s look at an example to understand it well.

Suppose we have a method named as getItem(), whose purpose is to get few records from a table, from the database.

const getEmployee = function(employeeId, callback) {
mysql.getItem("employee",employeeId, (error, employeeDetails) => {
if (error) {
callback(error)
} else {
callback(null,employeeDetails);
}
})
};

In this piece of code, we have a method by the name mysql.getItem() being called with a table name, an employee ID and a callback. If mysql.getItem() gives an error while executing, then that error is passed to the callback else the employee details are passed to the callback. This idiomatic pattern is referred to as an error-first callback. With this pattern, a callback function is passed to the method as an argument. When the operation either completes or an error is raised, the callback function is called with the Error object (if any) passed as the first argument. If no error was raised, the first argument will be passed as null. We can make a call to the above getEmployee() method by:


getEmployee("EMP1", (error,result) => {
if(error) {
console.log(error);
}else{
console.log(result);
}
});

While working with callbacks, we may bump into Promises, that’s altogether a separate concept which is used to make code asynchronous. We can take that concept in some other future blog. So, to conclude, Callbacks are great. When implemented right, good use of callbacks and asynchronous code can provide huge improvements to the speed and scalability of your code.

 

I hope this blog will help you to understand the basics of callbacks.

Thank you!!

References:
Node js error first callbacks

 

Knoldus-blog-footer-image

Written by 

Vinisha Sharma is a software consultant having more than 6 months of experience. She thrives in a fast pace environment and loves exploring new technologies. She has experience with the languages such as C, C++, Java, Scala and is currently working on Java 8. Her hobbies include sketching and dancing. She believes Optimism and a learning attitude is the key to achieve success in your life

Leave a Reply

Knoldus Pune Careers - Hiring Freshers

Get a head start on your career at Knoldus. Join us!