Javascript Essentials

"CALLBACK FUNCTION"​​

Callback

Functions are first-class objects, we can pass a function as an argument in another function and later execute that passed-in function or even return it to be executed later.

Callback or Higher Order Function

A callback function, also known as a higher-order function, is a function that is passed to another function (let’s call this other function “other Function”) as a parameter, and the callback function is called (or executed) inside the other Function.

 

A callback function is essentially a pattern (an established solution to a common problem), and therefore, the use of a callback function is also known as a callback pattern.

Simple Example

var friends = ["Mike", "Stacy", "Andy", "Rick"];
​
friends.forEach(function (eachName, index){
console.log(index + 1 + ". " + eachName); // 1. Mike, 2. Stacy, 3. Andy, 4. Rick​
});

How Callback Functions Work?

 

We can pass functions around like variables and return them in functions and use them in other functions. When we pass a callback function as an argument to another function, we are only passing the function definition. We are not executing the function in the parameter.

 

In other words, we aren’t passing the function with the trailing pair of executing parenthesis () like we do when we are executing a function.

Callback Functions Are Closure

 

When we pass a callback function as an argument to another function, the callback is executed at some point inside the containing function’s body just as if the callback were defined in the containing function. This means the callback is a closure.

Pass Parameters to Callback Functions

 

	//Global variable​
​var generalLastName = "Clinton";
​
​function getInput (options, callback) {
    allUserData.push (options);
​// Pass the global variable generalLastName 
//to the callback function​
    callback (generalLastName, options);
}

Make Sure Callback is a Function Before Executing It

 

function getInput(options, callback) {
    allUserData.push(options);
​
    // Make sure the callback is a function​
    if (typeof callback === "function") {
    // Call it, since we have confirmed it is callable​
        callback(options);
    }
}

Problem When Using Methods With The this Object as Callbacks

 

// Define an object with some properties and a method​
​// We will later pass the method as a callback function to another function​
​var clientData = {
    id: 094545,
    fullName: "Not Set",
    // setUserName is a method on the clientData object​
    setUserName: function (firstName, lastName)  {
        // this refers to the fullName property in this object​
      this.fullName = firstName + " " + lastName;
    }
}
​
​function getUserInput(firstName, lastName, callback)  {
    // Do other stuff to validate firstName/lastName here​
​
    // Now save the names​
    callback (firstName, lastName);
}
getUserInput ("Barack", "Obama", clientData.setUserName);
console.log (clientData.fullName);// Not Set​
​// The fullName property was initialized on the window object​
console.log (window.fullName); // Barack Obama

Fix issue with call and apply

//Note that we have added an extra parameter for the callback object,
// called "callbackObj"​
​function getUserInput(firstName, lastName, callback, callbackObj)  {
    // Do other stuff to validate name here​
​
    // The use of the Apply function 
    //below will set the this object to be callbackObj​
    callback.apply (callbackObj, [firstName, lastName]);
}

Multiple Callback Functions Allowed

function successCallback() {
    // Do stuff before send​
}
​
​function successCallback() {
    // Do stuff if success message received​
}
​
​function completeCallback() {
    // Do stuff upon completion​
}
​
​function errorCallback() {
    // Do stuff if error received​
}
​
$.ajax({
    url:"http://fiddle.jshell.net/favicon.png",
    success:successCallback,
    complete:completeCallback,
    error:errorCallback
​
});

“Callback Hell” Problem And Solution

 

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();
                    });
                });
            });
        });
    });
});
Made with Slides.com