InterviewVault
Welcome back, Sujit Kumar Mishra
Admin
SK Mishra
Revision Mode
Document technical questions and best-practice answers.
What is the callback function in JavaScript? Where did we use this callback function actually? Can we use this callback function from on class to another class in the JavaScript, here class is nothing but different AJAX calls, means can we use callback function for certain AJAX call and the after getting it's response, can we again use the same callback function for the another AJAX call which we are doing from the success response of the first AJAX call?
A callback function in JavaScript is a function that is passed as an argument to another function and is executed after some operation is completed.
Where do we use callback functions?
Callback functions are commonly used in asynchronous operations like AJAX calls, setTimeout, event listeners, or when you want to run some code only after another function finishes its task.
Can we use the same callback function across different AJAX calls or classes?
Yes, you can use the same callback function for multiple AJAX calls. For example, you can call an AJAX request, and in its success handler (callback), you can make another AJAX call and reuse the same callback function again. In JavaScript, functions are treated as first-class citizens, so you can pass them around and reuse them wherever needed.
Example:
function handleResponse(data) {
console.log("Received data:", data);
// You can process the data or trigger another action here
}
// First AJAX call
$.ajax({
url: 'api/first',
success: function(response) {
handleResponse(response);
// Second AJAX call inside the success of the first
$.ajax({
url: 'api/second',
success: handleResponse // Reusing the same callback
});
}
});
Summary:
1: Callback = function passed to another function to run later.
2: Used in AJAX, timers, and event handling.
3: You can reuse the same callback for multiple AJAX calls, even across different parts of your code.