Conjunction(junction, callbackFunction)♫

Coming from a background of purely Object-Oriented programming, the functional programming paradigm was one of the hardest things for me to grasp. In Javascript functions exist as objects and can be passed into other functions much like other base data types (i.e. strings, integers, floats, etc.) The function call within another function is the basis for the callback. In the following I hope to cover what it is, why it’s important, and how it can be implemented.
Earlier I mentioned that a callback function is one passed as an argument into another function. This is also commonly referred to as a Higher Order Functions.
Callback functions are closures. Closures are functions that have scope over outer (immediate) functions.
Sometimes we write functions containing many functions because the task requires many smaller steps. Instead of writing giant blocks of code, we can simplify (for the sake of readability), into smaller chunks. Say if you needed to bake some bread…
Implementing Callbacks (Basic Principles)
when using callback functions we want to stick to using named or anonymous (un-named) functions.
Make Sure callBack is a Function Before Executing It
it is generally a good idea to test that your callBack is a function. because of the mutable nature of arguments being passed into your parent function, the callBack might be passed in as a non-function resulting in a runtime error.
If you don’t break your functions into smaller managable chunks…
you get something known as a callBack hell:
var p_client = new Db('integration_tests_20', new Server("127.0.0.1", 27017, {}), {'pk':CustomPKFactory});
p_client.open(function(err, p_client) {
p_client.dropDatabase(function(err, done) {
p_client.createCollection('test_custom_key', function(err, collection) {
collection.insert({'a':1}, function(err, docs) {
collection.find({'_id':new ObjectID("aaaaaaaaaaaa")}, function(err, cursor) {
cursor.toArray(function(err, items) {
test.assertEquals(1, items.length);
// Let's close the db
p_client.close();
});
});
});
});
});
});the takeaway:
Name your functions and pass arguments to them in the callBack instead of placing anonymous functions entirely in the arguments of the parent function.
Make your functions Modular for readability and sanity. Don’t make a trainwreck.
knowledge of callBack functions will help us understand other concepts like asynchronous functions, AJAX, and how to manipulate data after a fetch request to a server. No promises though (pun intended).