4 ms·
Hmm. Lemme see if I can explain this. Javascript uses "function references" in a similar fashion to C's "function pointers". This... function fooAllTheBars(
by mhink 10y ago
Hmm. Lemme see if I can explain this.
Javascript uses "function references" in a similar fashion to C's "function pointers". This...
function fooAllTheBars() { /* ...quux... */ }
...is a function declaration statement which binds a callable reference to my function to the name `fooAllTheBars`. That said, we can express an "anonymous function declaration" as an rvalue, so we can also bind the function to a name ourselves:
const fooAllTheBars = function() { /* ...quux... */ };
Since this is a function reference, I could pass it into a function like this:
setTimeout(fooAlltheBars, 1000);
...which would tell the JS runtime to wait 1000ms and then execute `fooAllTheBars`. I could also express this using an anonymous function:
setTimeout(function() { /* ...quux... */ }, 1000);
This is all fine and dandy, but suppose I also had a function like this:
function quuxify(value, calculator, cb) {
calculator(value, function(err, calcResult) {
if (!err) {
cb(calcResult.toFixed(2));
}
});
}
function bazzify(success, failure) {
quuxify('foo',
function(value, cb) {
setTimeout(function() {
if (value > 100) {
cb("too high!", null);
} else {
cb(null, value - 10);
}
}, 1000);
}, success);
}
bazzify(console.log, () => {});
This is, admittedly, a bit of a pathological example than the simple "nested callback problem", and the code makes even less sense because "bazzify" and "quuxify" don't actually mean anything, but I think it's a better illustration of the problem at hand.
Basically, if you get into callback hell, your control flow starts bouncing around like a pinball hitting bumpers, and figuring out why is nearly impossible (unless you want to dig through fifteen levels of anonymous functions). And the sad part is that in most cases, you can't avoid it altogether because there's something fundamentally asynchronous like a `setTimeout` or an `xmlHttpRequest` waiting at the end of the call stack.