Callbacks
Functions are first class objects in JS. Meaning, you can pass a function as an argument into another function and
execute as per the need.
Asynchronous callbacks are often used as a continuation of the program after an async operation.
Callbacks are by far the most common way that asynchrony in JS programs (Before ES6 promises).
Imagine you have an ajax utility to fetch a resource and based upon the result you need to make further request
// Nested callbacks
listen("click", function (event) {
ajax("http://example.com/first", function (respone1) {
if (response1) {
ajax("http://example.com" + response1, function (response2) {
console.log("Response", response1 + response2)
})
}
})
})
One of the problem with Callbacks, easily we end up in nested callbacks, or sometimes it is referred to as
Callback hell. But there is more to Callback hell than just nested callbacks. It is difficult to imagine sequential way
of flow using callbacks, it is always jumpy when you have more async callbacks
doA(function () {
doC();
doD(function () {
doF();
});
doE();
});
doB();
Outputs: A -> B -> C -> D -> E -> F (if all the above functions are async)
what if doA() or doD() aren't async. The output would be A -> C -> D -> F -> E
Handling Failures
There is no norm how to handle error handling in Callbacks. Few libraries (NodeJs API) follow err
first argument
approach followed by actual response.
function response(err, data) {
if (err) {
console.error(err);
} else {
console.log(data);
}
}
- Each team or library follows different conventions of handling callbacks and how they do error handling.
-
err
anddata
needs to be checked for all callbacks which adds more redundant code. Imagine you have to do for sequence of async callbacks A -> B -> C. - Nesting along with error handling and redundant checks are the ones which make Callbacks Hell
Trust issues with Callbacks
Imagine you have a third party utility to do certain async action and post that your callback executes some important
stuff.
thridParty.doAction(function () {
// Important stuff for your app goes here which needs to be executed
})
What if there is a bug in third party utility, and probably you must think of different possibilities
- If the callback is never called
- If the callback is called more than once
- How errors/exceptions are handled? Are they swallowed or propagated to the callback
Above trust issues with callback hell and more boilerplate code for error handling are bottleneck for scaling
applications. That lead us to next asynchronous way of handling Promises
Top comments (0)