Callbacks in JavaScript: Why They Exist

What is callback function
Callback function is just a simple function which is passed as an argument to another function.
This was previously used to handle asynchronous tasks.
function hof(callback){
callback('HI');
}
function log(value){
console.log(value);
}
fn(log); //output - HI
In the above example log function is called Callback function because it is passed as an argument to another function.
Why callbacks are used in asynchronous programming
There are 3 ways to handle asynchronous tasks completion out of which one is callback functions.
Let us understand what does handling asynchronus tasks means?
The function which is invoked when an event occurs like click, hover is called Event Handler and click is the event. This Event handler is actually a callback function.
const clickEventHandler = ()=> { console.log('You clicked'); }
body.addEventListener('click', clickEventHandler);
So after a click event completes, we need some function to execute which will do something.
Similarly, Asynchronous task is like an event. After it has been done executing, there need to be some handler that will be invoked and that handler is callback.
Callback is a mechanism to handle asynchronous tasks.
Code example
I want to do 3 asynchronous tasks which are dependent on each other.
1 - Hit some API
2 - Read File
3 - Merge data and Update DB
// dependent async tasks create problem
function hitAPI(callback) {
//this function can call the callback anywhere it wants that is inversion of control problem
setTimeout(() => {
console.log('Api data fetched');
callback('data');
}, 2000);
}
function readFile(callback) {
setTimeout(() => {
console.log('File Read success');
callback('data')
}, 2000);
}
function saveInDb(callback) {
setTimeout(() => {
callback()
}, 2000);
}
// hitAPI -> readFile -> saveInDb
console.log('hello 1');
//------------------------------------------------------------------------
//Handling the async tasks
hitAPI((data) => {
readFile((data) => {
saveInDb((data) => {
console.log('Data saved in db');
})
})
})
//The above is the inversion of control problem and pyramid of doom
console.log('hello 2');
console.log('hello 3');
Issues in using callback function
When there are multiple dependent asynchronous, it causes some issues:
Inversion of Control - It means that we have no control on when and how our callback is invoked. We assume that the function will invoke it correctly. Examples :
Callback not called
Callback called early
Callback called twice
Pyramid of Doom / Callback Hell - It means that the code will start looking like a pyramid at some point which is hard to maintain and read.
Hard to debug
Hard to read
Solution of Callback function
Promises then, catch, finally
Async / Await
Key takeaways :
Callback is just a mechanism to handle async tasks
Problem arises where are too many dependent asynchronous tasks





