22
loading...
This website collects cookies to deliver better user experience
Synchronous: callbackFn
executed immediately.
Asynchronous: callbackFn
is chained with a promise and it will be invoked, after that promise fulfills or rejects.
function myFunction(callback){
callback();
}
// passing a function as an argument
myFunction(function(){
console.log("Hello World.");
});
myFunction()
expects an argument as its parameter. That's why an anonymous function has been given as an argument to myFunction()
.myFunction
body, the argument has been invoked. And that function will console.log
Hello World
to the console. callback
function.function func1(){
console.log("Hello 1");
}
function func2(){
console.log("Hello 2");
}
func1(); // Hello 1
func2(); // Hello 2
console.log
Hello 1
and Hello 2
respectively. 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");
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.Hello 1
it will print Hello 2
, after that it will log the response from loadData()
function.event loop
.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.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);
printHello()
function takes a value as an argument and concat it with the string Hello
and log to the console.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.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.Note that the onreadystatechange
function is also a callback function. This function is called when it completes the request and sends a response.