Understanding the callback function (callback) "Go" in JavaScript

Source: Internet
Author: User
Tags types of functions what callback

In Javascrip, a function is a built-in class object, which means that it is a type of object that can be used for the management of built-in objects just like other objects of the string, Array, number, and object classes. Because the function is actually an object, it can be "stored in a variable, passed to (another) function by argument, created inside a function, and returns the result value from the function." Because function is a built-in object, we can pass it as an argument to another function, defer execution to the function, or even return it after execution. This is the essence of using a callback function in JavaScript. The remainder of this article will fully learn the JavaScript callback function. The callback function may be the most widely used functional programming technique in JavaScript, and perhaps just a small piece of JavaScript or jquery code will leave a mystery to the developer, and reading this article may help you eliminate the mystery.

The callback function comes from a well-known programming paradigm- functional programming , at the basic level, where functional programming specifies the parameters of a function. Functional programming Although the current scope of use has become smaller, but it has been "professional smart" programmers as a kind of difficult to understand technology, previously, and the future will be so.

Fortunately, functional programming has been elaborated by the General people like you and me can also understand and use. One of the main techniques of functional programming is the callback function, which you will soon read that implementing a callback function is as simple as passing a generic parameter variable. This technology is so simple that I wonder why it is often included in the high-level topic of JavaScript.

What is a callback or advanced function?

A callback function is considered an advanced function, an advanced function that is passed as a parameter to another function (called "otherfunction"), and the callback function is called (or executed) within the otherfunction. The essence of a callback function is a pattern (a pattern that solves common problems), so a callback function is also called a callback pattern.

Consider the following callback functions that are commonly used in jquery:
//Note that the item in the click method‘s parameter is a function, not a variable.
//The item is a callback function
$("#btn_1").click(function() {
  alert("Btn 1 Clicked");

As seen in the previous example, we pass a function to the parameter of the click Method, and the click Method invokes (or executes) the callback function we pass to it. This example gives a typical way to use the callback function in JavaScript and is widely used in jquery.

Savor a typical example of another basic javascript:

var friends = ["Mike", "Stacy", "Andy", "Rick"];

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

Once again, we passed an anonymous function in the same way (a function without a function name) to the Foreach method as a foreach parameter.

So far, we have passed an anonymous function as a parameter to another function or method. Before looking at other more complex callback functions, let's take a look at how callbacks work and implement a callback function of our own.

How is the callback function implemented?

We can use a function like a variable, as an argument to another function, in another function as the return result, and call it in another function. When we pass a callback function as a parameter to another function, we pass only the definition of the function and do not execute it in the argument.

When the containing (called) function has a callback function defined in the parameter, it can be called at any time (that is, callback).

This means that the callback function is not executed immediately, but rather "callback" it (as its name) in the specified position within the function body containing the function. So, even if the first example of jquery looks like this:

//The anonymous function is not being executed there in the parameter. 
//The item is a callback function
$("#btn_1").click(function() {
  alert("Btn 1 Clicked");

The anonymous function is called in the function body of the Click function, even if there is no name, it can be accessed by the containing function through the arguments object.

The callback function is a closed packet.
When you pass a callback function as a parameter to another function, the callback function is executed somewhere within the body of the containing function function, as if the callback function is defined in the body of the function that contains the function. This means that the callback function is closed, and if you want to learn more about closures, refer to the author's other post understand JavaScript Closures with Ease. It is known that the closure function can access the scope of the containing function, so the callback function can access the variable that contains the function, even the global variable.

Basic principles of implementing callback functions

Simply put, there are a few principles to follow when implementing a callback function yourself.

Use a named function or an anonymous function as a callback
In the preceding jquery and foreach examples, we define anonymous functions in the parameters that contain the function, which is one of the common forms of using the callback function, and the other is often used in the form of defining a function with a name and passing the function name as an argument to another function, for example:

// global variable
var allUserData = [];

// generic logStuff function that prints to console
function logStuff (userData) {
    if ( typeof userData === "string")
    else if ( typeof userData === "object")
        for (var item in userData) {
            console.log(item + ": " + userData[item]);



// A function that takes two parameters, the last one a callback function
function getInput (options, callback) {
    allUserData.push (options);
    callback (options);


// When we call the getInput function, we pass logStuff as a parameter.
// So logStuff will be the function that will called back (or executed) inside the getInput function
getInput ({name:"Rich", speciality:"JavaScript"}, logStuff);
//  name: Rich
// speciality: JavaScript

Passing parameters to the callback function
Because the callback function is executed just like a normal function, we can pass parameters to it. You can pass a callback function as a parameter to any property that contains a function (or a global property). In the previous example, we passed the options containing the function as arguments to the callback function. The following example lets us pass a global variable or local variable to the callback function:

//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 the callback is a function before executing
Before calling, it is often advisable to ensure that callbacks passed in through parameters are a required function. In addition, making the callback function optional is also a good practice.

Let's refactor the GetInput function in the example above to make sure that the callback function is properly checked.

function getInput(options, callback) {

    // Make sure the callback is a function
    if (typeof callback === "function") {
    // Call it, since we have confirmed it is callable

If the GetInput function is not properly checked (checking whether callback is a function or passed in by argument), our code will cause a run-time error.

Problems with the callback function that contains this object
When the callback function is a method containing the This object, we must modify the method that executes the callback function to protect the contents of this object. Otherwise the This object will point to the Global Window object (if the callback function is passed to the global function), or to the containing function. Let's take a look at the following code:

// 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);

In the following example code, when Clientdata.setusername is executed, This.fullname does not set the property fullname in the Clientdata object, but instead sets the FullName in the Window object. Because Getuserinput is a global function. This behavior occurs because the this object points to the Window object in the global function.

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

Protect this object with the call or Apply function

We can solve the problem in the previous example by using the call or Apply function. So far, we know that every function in JavaScript has two methods: Call and apply. These methods can be used to set the contents of this object inside a function and to pass the content to the object that the function argument points to.

Call takes the value of used as the This object inside the function as the first parameter, and the remaining Arguments to is passed to the function is passed individually (separated by commas of course). The Apply function ' s first parameter is also the value of be used as the thisobject inside the function and the last PA  Rameter is a array of values (or the arguments object) to pass to the function. (The paragraph is too awkward to translate, let the original experience)

This sounds complicated, but let's look at how easy it is to use apply and call. To solve the problem in the previous example, we use the Apply function as follows:

//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]);

By using the Apply function to set the This object correctly, we can now execute the callback function correctly and set the FullName property in the Clientdata object correctly.

// We pass the clientData.setUserName method and the clientData object as parameters. The clientData object will be used by the Apply function to set the this object
?getUserInput ("Barack", "Obama", clientData.setUserName, clientData);

// the fullName property on the clientData was correctly set
console.log (clientData.fullName); // Barack Obama

We can also use the call function, but in this case we use the Apply function.

Multiple callback functions are also allowed
We can pass multiple callback functions to another function, just like passing multiple variables. This is a typical example of an AJAX function using jquery:

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


Questions and solutions for "Callback Hell"

Asynchronous code execution is a simple way to execute in any order, and sometimes it is quite common to have many levels of callback functions, and you look like the following code. The messy code below is called "Callback hell" because it's a cumbersome code that contains a lot of callbacks. I saw this example in Node-mongodb-native, MongoDB drives node. js. The sample code is like this:

var p_client = new Db(‘integration_tests_20‘, new Server("", 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

You are unlikely to encounter this problem in your own code, but if you run into it (or stumble into it later), there are two ways to solve the problem.

    1. Name and define your function, and pass the function name as a callback instead of defining an anonymous function in the parameter list of the main function.
    2. Modularity: Divide your code into modules so that you can spare a chunk of code to do special work. You can then introduce this model into your large application.


Implement your own callback function

Now you fully understand (I'm sure you understand that if you don't read it quickly again) JavaScript uses the features of the callback and see that the callbacks are used so simple but powerful. You should see if your code has the opportunity to use the callback function, and you can consider using callbacks when you have the following requirements:

    • Avoid duplicate code (dry-do not Repeat yourself)
    • It's better to implement abstractions where you need more common functionality (you can handle various types of functions).
    • Enhanced maintainability of code
    • Enhance the readability of your code
    • There are more custom features.

Implementing your own callback function is simple, in the following example, I can create a function to complete the work: Get user data, use user data to generate a common poem, use user data to welcome users, but this function will be a messy function, everywhere is if/else judgment, There are even many restrictions that cannot be performed on other functions that the application may need to process user data.

Instead, I let the implementation add a callback function, so that the main function gets the user data and can pass the user's full name and gender to the parameters of the callback function and execute the callback function to accomplish any task.

In short, the Getuserinput function is generic and can perform multiple callback functions with various functions.

// First, setup the generic poem creator function; it will be the callback function in the getUserInput function below.
function genericPoemMaker(name, gender) {
    console.log(name + " is finer than fine wine.");
    console.log("Altruistic and noble for the modern time.");
    console.log("Always admirably adorned with the latest style.");
    console.log("A " + gender + " of unfortunate tragedies who still manages a perpetual smile");

//The callback, which is the last item in the parameter, will be our genericPoemMaker function we defined above.
function getUserInput(firstName, lastName, gender, callback) {
    var fullName = firstName + " " + lastName;

    // Make sure the callback is a function
    if (typeof callback === "function") {
    // Execute the callback function and pass the parameters to it
    callback(fullName, gender);

Call the Getuserinput function and pass the Genericpoemmaker function as a callback:

getUserInput("Michael", "Fassbender", "Man", genericPoemMaker);
// Output
/* Michael Fassbender is finer than fine wine.
Altruistic and noble for the modern time.
Always admirably adorned with the latest style.
A Man of unfortunate tragedies who still manages a perpetual smile.

Since the Getuserinput function only handles input from the user data, we can pass any callback function to it. For example, we can pass a greetuser function like this.

function greetUser(customerName, sex)  {
   var salutation  = sex && sex === "Man" ? "Mr." : "Ms.";
  console.log("Hello, " + salutation + " " + customerName);

// Pass the greetUser function as a callback to getUserInput
getUserInput("Bill", "Gates", "Man", greetUser);

// And this is the output
Hello, Mr. Bill Gates

As in the previous example, we called the same getuserinput function, but this time we performed a completely different task.

As you can see, the callback function provides a wide range of functions. Although the example mentioned earlier is very simple, think about how much you can save and how to better abstract your code when you start using a callback function. Come on! When you get up in the morning, think about it before you go to bed at night, and think about it when you rest ...

We often note the following when using callback functions in JavaScript, especially today's web application development, in third-party libraries and frameworks

    • Asynchronous execution (such as reading a file, sending an HTTP request)
    • Event monitoring and processing
    • To set the timeout and time interval method
    • Generalization: Code Simplicity
This article mainly describes the understanding of the callback function in JavaScript (callback), this article focuses on the concept of callback function understanding, the need for friends can refer to the following

Recently, looking at Express, eyeful, everywhere is the use of callback functions as parameters of the function. If this concept is not understood, Nodejs, express code will see a mess. Like what:

Copy the code code as follows:
App.use (function (req, res, next) {
var err = new Error (' not Found ');
Err.status = 404;
Next (ERR);
The app is an object, use is a method, the parameter of the method is an anonymous function with parameters, and the function body is given directly at the back. How does this code understand? Let's begin by understanding the concept of callback functions.
First of all, in JS, the function is also an object, you can assign a value to the variable, can be placed as a parameter in the function's argument list. Like what:
Copy the code code as follows:
var dosomething = function (A, B)
return a + B;
The meaning of this code is to define an anonymous function, which, in addition to having no name, is nothing like a normal function. The anonymous function is then assigned a value to the variable dosomething. Next we call:
Copy the code code as follows:
Console.log (dosomething (2,3));

This will output 5.

The callback function, which is placed in a parameter list of another function (such as parent), is passed as a parameter to the parent and then executed at a location in the parent function body. To be abstract, look at an example:

Copy the code code as follows:
To illustrate the concept of callback
var doit = function (callback)
var a = 1,
b = 2,
c = 3;
var t = callback (A,B,C);
return T + 10;
var d = doit (function (x, y, z) {
return (X+Y+Z);
Console.log (d);
Define the doit function first and have a parameter callback. This callback is the callback function, the name can be arbitrarily taken. Look at the function body, first define three variables A,b,c. Then call the callback function. Finally, a value is returned.

The doit function is called below. Note that the definition of doit just now, callback is not defined, so just did not know what callback is for. This is actually very good understanding, we usually define the function, the parameters are only given a name, such as a, in the function body to use a, but the whole process is not aware of what is a, only when the function is called to specify the specific value of a, such as 2. Turn back, when calling doit, We need to specify what the callback is. As you can see, this function completes a sum function.

The execution of the above code is:

Call the doit function, the parameter is an anonymous function, enter the function body of doit, define A,B,C first, then execute the anonymous function just now, the parameter is a,b,c, return a T, and finally return a t+10 to D.

Back to the original example, App.use (...) is a function call. We can imagine that a use method must have been defined before, but not given here. A comparison of these two examples can be understood immediately.

In the use of Nodejs, Express, it is not possible for each method or function we have to find its function definition to look at. So just know what parameters are passed to the callback in that definition. Then, when invoking a method or function, we define the anonymous function in the parameter to accomplish some function.


An analysis of callback methods in JavaScript

Submission: Junjie font: [Increase decrease] Type: Reprint time: 2015-03-15 I want to comment

This article mainly introduces the Callback method in JavaScript, this article explains what is Callback, Javscript Callback, Callback is what, Callback instances and other content, the need for friends can refer to the next

What is callback

A callback function is a function that is called through a function pointer. If you pass the pointer (address) of the function as an argument to another function, when the pointer is used to invoke the function it points to, we say this is a callback function. The callback function is not called directly by the implementing party of the function, but is invoked by another party when a particular event or condition occurs, and is used to respond to the event or condition.

The explanation looked complicated and found a better explanation.

You go to a shop to buy things, just what you want to have no goods, so you left your phone in the shop clerk, after a few days the store has goods, the clerk called you, and then you received a call to the store to pick up the goods. In this example, your phone number is called a callback function, you leave the phone to the clerk called the registration callback function, the store later in the goods called triggered the callback associated event, the clerk called you called Call callback function, you go to the store to fetch goods called response callback event. The answer is complete.

In javascript:

Function A is passed as a parameter (a function reference) to another function B, and this function B executes function A. Let's just say that function A is called a callback function. If there is no Name (function expression), it is called an anonymous callback function.
In fact, the function is passed as a parameter.

Javscript Callback

Throw all those complicated explanations in the trash, and see what callback is.

What is callback?

In jquery, the method of hide is probably the same.

$ (selector). Hide (Speed,callback)

$ (' #element '). Hide (+, function () {
callback function
We just need to write a simple function inside.
Copy the code code as follows:
$ (' #element '). Hide (+, function () {
Console.log (' Hide ');
There is a small note in this: the Callback function executes after the current animation 100% is complete. Then we can see the real phenomenon, and when the element ID is hidden, hide is output in the console.

It also means:

Callback actually, when a function is executed, the function that is now executing is called the callback function.

Callback Effect

Normally functions are executed sequentially, but JavaScript is an event-driven language.

function Hello () {
Console.log (' Hello ');

function World () {
Console.log (' World ');

Hello ();
World ();

So it will normally be executed sequentially, but when the world event is executed for a long time.
function Hello () {
SetTimeout (function () {
Console.log (' Hello ');
}, 1000);

function World () {
Console.log (' World ');

Hello ();
World ();

Then this is not the case, this time will output world, and then output hello, so we need to callback.

Callback Instances

A simple example is as follows

function Add_callback (P1, p2, callback) {
var my_number = p1 + p2;
Callback (My_number);


Add_callback (5, function (num) {
Console.log ("call" + num);

In the example we have a add_callback function that receives three parameters: the first two are the two parameters to add, the third parameter is the callback function. When the function executes, returns the result of the addition and outputs ' call 20 ' to the console.

Understanding the callback function (callback) "Go" in JavaScript

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.