1. First, what is a function?
A function is simply a block of code that we can call when we need it.
function greet() {
console.log("Hello Tony");
}
greet();
Output:
Hello Tony
2. So what is a callback?
A callback function is a function that we give to another function as an argument, so that the other function can call it later. A callback function is intended to be executed later.
function greet() {
console.log("Hello!");
}
function execute(callback) {
callback();
}
execute(greet);
We are passing the greet function into execute.
Inside execute:
function execute(callback) {
callback();
}
callback now contains the greet function. so the callback runs the greet function.
Output:
"Hello"
There are two types of callback functions:
- Synchronized Task Callback
- Asynchronized Task Callback
In Synchronized Task, The function executes the code line by line in an order.
const hotel = (serveOrder) => {
console.log("vegetable cutting");
console.log("vessel washing");
console.log("cooking");
console.log("Serve food");
serveOrder();
console.log("Clean Table");
};
const eatBriyani = () => {
console.log("Eating");
};
hotel(eatBriyani);
Output:
vegetable cutting
vessel washing
cooking
Serve food
Eating
Clean Table
In the case of Asynchronized Task, the Particular assigned task will be processed parallelly with the other synchronized task.
const hotel = (serveOrder) => {
console.log("Vegitable cutting");
console.log("Vessel washing");
console.log("Cooking");
console.log("serve food");
setTimeout(() => {
console.log("Timer");
}, 2000);
serveOrder();
};
const eatBriyani = () => {
console.log("Eating");
};
hotel(eatBriyani);
Output:
Vegitable cutting
Vessel washing
Cooking
serve food
Eating
(The below output is executed after 2seconds)
Timer
Asynchronous Operations:
Callbacks are essential for handling non-blocking tasks like fetching data from an API, reading files, or using setTimeout timers, ensuring subsequent code runs only after the background task finishes
Top comments (0)