A callback is an executable code that is passed as an argument to another function or code and executes after some time or certain condition. So that’s why we can also say call after function to a callback function. Execution can be of two types first one is immediate (synchronous) callback and another one is later (asynchronous). But to understand the callback function you need to know the basic of the javascript function, closure.
Why do we need Callback?
function morningMsg() {
console.log("Good Morning");
}
function nightMsg() {
console.log("Good Night");
}
morningMsg(); //Good Morning
nightMsg(); // Good Night
In this example, morningMsg calls first and nightMsg call after morningMsg msg so morningMsg response first and nightMsg responds after morningMsg so everything is fine but what else if morningMsg is an API call or part of timer functions?
function morningMsg() {
setTimeout(function() {
console.log("Good Morning");
}, 1000)
}
function nightMsg() {
console.log("Good Night");
}
morningMsg();
nightMsg();
// Good Night
// Good Morning
Now you can see that nightMsg response is first and morningMsg response after nightMsg. just because of morningMsg will take time to 1000 milliseconds. So in this time duration nightMsg replay. So now we can say the javascript function doesn’t wait to complete the function call or function response.
Create a Callback
function morningMsg(name, callback) {
setTimeout(function() {
console.log("Good Morning", name);
callback(name);
}, 1000)
}
function nightMsg(name) {
console.log("Good Night", name);
}
morningMsg("John", nightMsg);
// Good Morning John
// Good Night John
Callback with real-world data
function morningMsg(name, callback) {
$.ajax({
url: "Name api that gives user name",
success: function(name) {
if (name) {
console.log("Good Morning", name);
callback(name);
}
},
error: function(err) {
console.error(err);
}
});
}
function nightMsg(name) {
console.log("Good Night", name);
}
morningMsg("John", nightMsg);
// Good Morning John
// Good Night John
Nested callback or complex callback
function morningMsg(name, callback) {
console.log("Good Morning", name);
setTimeout(function() {
callback(name);
}, 1000)
}
function afternoonMsg(callback) {
return function(name) {
console.log("Good Afternoon", name);
setTimeout(function() {
callback(name);
}, 1000)
}
}
function nightMsg(name) {
console.log("Good Night", name);
}
morningMsg("John", afternoonMsg(nightMsg));
// Good Morning John
// Good Afternoon John
// Good Night John
A lot of time nested callback creates a callback hell in which first of all callback depends on the upper callback result or response. So that time we need to be careful. In the next article, we will discuss how to handle that type of problem using promise.