Javascript Callbacks
Brief History of Callbacks
It all starts with the callback function.
A callback function is just a plain JavaScript function that is passed into another function as an argument.
That’s it. Nothing special.
This callback function can be used to return data, or to signal that some event took place.
If you’ve worked with web development you’ve definitely crossed paths with callbacks.
Think of a button click
event for a web page.
<button id="btnDoSomething">Click Me</button>
// callback function
const clickCallback = function(event) {
// do something
};
// get reference to the button on the page
const btn = document.getElementById('btnDoSomething');
// register function to be called when button click event fires
btn.addEventListener('click', clickCallback)
The addEventListener
subscribes a provided function to an event by name.
In this case we’re registering the clickCallback
function to the click
event type. The moment the button publishes a click
event all the subscribed event listener functions are invoked.
With a callback you could start a long running function, pass the callback function to signal when it’s done, and later handle the response data.
Callback functions worked great for enabling ‘asynchronous’ operations.
Sounds good, right?
So, what is wrong with callbacks? I’ll give you a hint…
Callback Hell
What is callback hell?
If you’ve ever read Dante’s Inferno (or Google it) the first thing you learn is there are multiple levels to hell. It just keeps getting deeper and deeper.
In callback hell, each level of the code, in this case, becomes more brittle than the one before it.
If you’re squeamish look away now.
Let’s see how quickly a simple workflow could fall into callback hell.
function moveLevel(name, callback) {
let err, data;
// stuff happened here to return error or data
callback(err, data);
}
// I have a bad feeling about this
return moveLevel('limbo', function(err, data) {
return moveLevel('lust', function(err, data) {
return moveLevel('gluttony', function(err, data){
return moveLevel('greed', function(err, data){
return moveLevel('anger', function(err, data){
return moveLevel('heresy', function(err, data){
return moveLevel('violence', function(err, data){
return moveLevel('fruad', function(err, data){
return moveLevel('treachery', function(err, data){
});
})
})
})
});
})
})
})
})
At this point we could turn our monitor sideways to see the beautiful pyramid.
Some unfortunate souls may have the magestic Crappalachian Mountains spanning across the monitor. At least it’s a scenic code hike.
So, how do we save ourselves from this fate?
The Promise
.