JavaScript callback function (callback)

What is the callback function

In computer programming, a callback is a piece of executable code that is passed as an argument to other code, which is expected to call back (execute) the argument at some convenient time
[引自 维基百科 callback]

The callback function is a piece of executable code segment, it is passed to the rest of the code as a parameter, its role in this when needed to facilitate the call (callback) code. (A bit like a function pointer ?? C language)

In one JavaScript object is a function, the same object can be passed as a parameter to the function, so the function may be passed to another function as a parameter, as a function of this parameter is the callback function.

Callback

function add(num1, num2, callback){
    var sum = num1 + num2;
    callback(sum);
}

function print(num){
    console.log(num);
}

add(1, 2, print);        //=>3

Anonymous callback function

function add(num1, num2, callback){
    var sum = num1 + num2;
    callback(sum);
}

add(1, 2, function(sum){
    console.log(sum);        //=>3
});

jQuery in a lot of use of the callback function

$("#btn").click(function() {
  alert("button clicked");
});

Why do we need a callback?

There is a very important reason - JavaScript is event-driven language. This means, JavaScript will not have to wait for a response to stop the current operation, but continue to listen when other events. View of a basic example:

function first(){
  console.log(1);
}

function second(){
  console.log(2);
}

first();
second();

As you might expect, first the function is executed first, and then  second be executed - console output following contents:

1
2
But if the function first contains some code can not be executed immediately will happen then? For example, we must send a request and then waits for a response API requests? To simulate this situation, we will use setTimeout , it is a call to the JavaScript function function after a period of time. We will function to simulate a delay of 500 milliseconds API request, the new code is a long way:
function First () {
 // simulation code delay 
  the setTimeout ( function () { 
the console.log ( . 1 ); 
  }, 500 ); 
} 

function SECOND () { 
  the console.log ( 2 ); 
} 

First (); 
SECOND ();

Now understand  setTimeout() it does not matter how this works, it is important that you see that we've  console.log(1); moved to the internal delay function 500 ms. So now call the function what happens?

2
1

Even if we first call the  first() function, we recorded output was in  second() after the function.

This is not a problem JavaScript function does not execute the order we want, but  JavaScript execution continues down  second() not wait until  first() the response issues.

So why you see this? Because you can not call functions one by one, and hope that they execute in the correct order. It is the way to ensure the implementation of the callback and then another piece of code after a code is completed .

The callback function What are the characteristics?

Not be executed immediately

When the callback function passed as a parameter to a function, passing just defined functions and will not be executed immediately. And regular function as callback function call function to go through the ()operator calls will be performed.

A closure

The callback function is a closure, that is to say it has access to the outer layer defined variable.

Before performing the type of judgment

The best confirmation before executing the callback function is a function.

function add(num1, num2, callback){
    var sum = num1 + num2;
    if(typeof callback === 'function'){
        callback(sum);
    }
}

this use of
note that the context in which this execution context defined callback function when the callback function is not called, but a function call context it is located.

var obj = {
    sum: 0,
    add: function(num1, num2){
        this.sum = num1 + num2;
    }
};

function add(num1, num2, callback){
    callback(num1, num2);
};

add(1,2, obj.add);
console.log(obj.sum);            //=>0
console.log(window.sum);        //=>3

The code calls the callback function of time in the global environment, so this point is window, the sumvalue is assigned to windowsthe.

On thisthe issue of the execution context can be applya solution.

var obj = {
    sum: 0,
    add: function(num1, num2){
        this.sum = num1 + num2;
    }
};

function add(num1, num2, callbackObj, callback){
    callback.apply(callbackObj, [ num1, num2 ]);
};

add(1,2, obj, obj.add);
console.log(obj.sum);            //=>3
console.log(window.sum);        //=>undefined

A plurality of transfer functions allows callbacks

A plurality of transfer function can callback functions, such as a typical example 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​
}
$.ajax({
    url: "http://fiddle.jshell.net/favicon.png",
    success: successCallback,
    complete: completeCallback,
    error: errorCallback
});

The callback function nesting

A callback function may be embedded in another callback, when nested, code maintenance and hard to read, this time may be named using a callback function to call the way, modular or management functions in this case, can also be used promise mode programming.

From node-mongodb-native, one for driving MongoDB Node.js brought in an example:

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();
                       });
                   });
               });
           });
       });
   });

 

 

Reference links:

1. https://cnodejs.org/topic/564dd2881ba2ef107f854e0b

2. https://juejin.im/post/594b3607128fe100650355c7

3. https://www.jianshu.com/p/84cc8732689c

Guess you like

Origin www.cnblogs.com/lfri/p/11872294.html