This content originally appeared on DEV Community and was authored by Prosen Ghosh
What is callback function?
Any function that is sent as a function argument is called a callback function. Which is then invoked inside the outer function to do some other task or action.
We can divide callback in 2 types.
Synchronous:
callbackFn
executed immediately.Asynchronous:
callbackFn
is chained with a promise and it will be invoked, after that promise fulfills or rejects.
Let's write a callback function.
function myFunction(callback){
callback();
}
// passing a function as an argument
myFunction(function(){
console.log("Hello World.");
});
In the snippet we can see that myFunction()
expects an argument as its parameter. That's why an anonymous function has been given as an argument to myFunction()
.
Inside the myFunction
body, the argument has been invoked. And that function will console.log
Hello World
to the console.
That anonymous function is called a callback
function.
Why do you need a callback function?
The callback function is often used to continue code execution after an operation has completed.
Let me show you 2 short code.
function func1(){
console.log("Hello 1");
}
function func2(){
console.log("Hello 2");
}
func1(); // Hello 1
func2(); // Hello 2
Calling this two function will console.log
Hello 1
and Hello 2
respectively.
That's the expected result. Right?
But what if we have to wait for an API call to finish? Will the above still going to work?
We are going to call an API to see what actually happens.
function loadData() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
console.log(JSON.parse(this.responseText));
}
};
xhttp.open("GET", "https://api.jsonbin.io/b/5a57a78efa0fa33d7b63d73e", true);
xhttp.send();
}
console.log("Hello 1");
loadData();
console.log("Hello 2");
We expected from the above code snippet that Hello 1
will be console.log
first, then the response from the loadData()
function and after that the Hello 2
will be console.log
in the console.
However, JavaScript does not work this way, it will not wait for the request to finish.
In the above code snippet, after printing Hello 1
it will print Hello 2
, after that it will log the response from loadData()
function.
Why???
Because of the event loop. The event loop is the secret behind JavaScript's asynchronous behavior.
I will write another day about the event loop
.
All you need to know now is that if there is some specified event (ex: browser API call, http/s call
) occurred in JavaScript, the JavaScript engine will execute the next code without waiting for that event to finish, and when the event is done, it shows/returns the result of that event.
So how do we get our expected output using callback?
The above code can be edited a little bit to get our expected result.
function printHello(value){
console.log("Hello " + value);
}
function loadData(callback, value) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
console.log(JSON.parse(this.responseText));
callback(value); // calling callback function here
}
};
xhttp.open("GET", "https://api.jsonbin.io/b/5a57a78efa0fa33d7b63d73e", true);
xhttp.send();
}
printHello(1);
loadData(printHello, 2);
The printHello()
function takes a value as an argument and concat it with the string Hello
and log to the console.
Now the printHello()
function and a value have been sent as an argument to the loadData()
function and the function has been called after the request finishes.
When the request is finished, the onreadystatechange
function will call, if the request is successful, first it will print the responseText
to the console, then the callback function will be called with the passed value which is 2
in this case.
This way we can get the expected output using the callback function.
Note that the
onreadystatechange
function is also a callback function. This function is called when it completes the request and sends a response.
This content originally appeared on DEV Community and was authored by Prosen Ghosh
Prosen Ghosh | Sciencx (2021-07-01T17:23:35+00:00) What is Callback Function?. Retrieved from https://www.scien.cx/2021/07/01/what-is-callback-function/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.