This is the 7th day of my participation in Gwen Challenge

JavaScript function callbacks

What is a callback function?

What exactly is a callback function? In fact, a callback function is also a function, it has all the characteristics of a function, it can have arguments and return values. If you give a single function, you can’t tell if it’s a callback. A callback function differs from a normal function in how it is called. A callback function is called only when a function is passed as an argument to another function, or to the host environment, and then the function is called inside the function or in the host environment.

Callbacks come in two different forms, synchronous and asynchronous. Usually, we need to pass a callback function to another executing function, so the big difference between synchronous and asynchronous callbacks is that synchronous callbacks are executed inside the executing function, while asynchronous callbacks are executed outside the executing function.

1. The quotes

There needs to be sequential execution time.

let x = function () {
    console.log("I am called from inside a function")};let y = function (callback) {
    console.log('do something');
    callback();
}
y(x);
/ / the result
//do something
//I am called from inside a function
Copy the code

When y(x) executes to callback(),x passes in its own function body and executes. So that’s y first and then x.

2. Callback functions

2.1 Examples of synchronous callback

Myarray.foreach (function) performs function on all data in an array

var myArray = ["1"."2"."3"."4"];
function handlerArray(indexName,index){ 
console.log(index + 1 + "." + indexName); 
}
myArray.forEach(handlerArray)
/ / 1. 1
/ / 2. 2
/ / 3. 3
/ / 4. 4
Copy the code

In this code, we use JavaScript’s native forEach method to enumerate each item in a number. The logic here is simple: to call forEach, use the handlerArray callback function as its argument; Inside the forEach method, the myArray array is iterated, and each element in the array calls the handlerArray callback once in turn. Because handlerArray is a parameter to forEach, and handlerArray is executed inside the forEach function, this is a synchronous callback. Synchronous callbacks are executed only on the stack.

2.2 Asynchronous Callback Example -setTimeout

Unlike synchronous callbacks, asynchronous callbacks are not executed inside their executing function, but at other locations (task queue) and at other points in time (setTimeout).

Take the following setTimeout code:

function foo(){
	alert("Hello")}setTimeout(foo,3000)
Copy the code

In this code, we use the setTimeout function. The first argument to setTimeout, foo, is a callback function. When V8 executes setTimeout, it returns immediately. Foo is called by V8 (from the queue to the stack). Foo is not executed inside the setTimeout function, so it is an asynchronous callback.

2.3 External declaration of the callback function after the call – code is more convenient to extend the method

A function that adds and multiplies two arguments before using the callback function

let calc = function(num1,num2,fn){
    if(fn==='add') {return num1+num2;
    }
    else if(fn==='multiply') {returnnum1*num2; }}console.log(calc(1.3,add));
console.log(calc(1.3,multiply));
/ / the result
/ / 4
/ / 3
Copy the code

After using the callback function

let add = function (num1, num2) {
    return num1 + num2;
}
let muiltply = function (num1, num2) {
    return num1 * num2;
}
let calc = function (num1, num2, callback) {
    // Ensure that the robustness is not broken by other things passed in
    if (typeof callback === "function") {
        returncallback(num1, num2); }}console.log('callback_add:', calc(3.3, add));
console.log('callback_muiltply:', calc(2.3, muiltply));
Copy the code

It is easier to add a new method to the calc function by defining the function and calling it through the callback.

Add a new function nothing to calc

// You can easily add functions to this library
let nothing = function (num1, num2) {
    console.log('These are your two numbers,${num1}.${num2}`)}Copy the code

It is then called under the calc function

console.log('callback_nothing', calc(2.3, nothing));
/ / the result
// here are your two numbers,2,3
Copy the code

conclusion

Through the above understanding of the two types of callback function, one is synchronous callback function, the callback function is executed inside the function that executes the callback function; One is asynchronous callbacks, which are not executed inside its executing function, but at other locations (in the Task queue) and at other points in time (setTimeout), making it easy to extend other methods with the same parameters through synchronous callbacks.