[Raiders] thorough understanding of the word JS callback (Callback) function

As the core, callback and asynchronous execution is closely related JS, is a must cross past a threshold.

So what exactly is a callback function (Callback), in fact, the callback function is not complicated, you can understand two key points:

1. The function can be called from another function as a parameter.

2. JS is an asynchronous programming language, which means that the order of execution JS code is not done step by step from top to bottom. Most languages ​​are synchronous programming language, for example, now we have three lines of code, then the system must be executed sequentially line by line down, the first line of execution is over, the implementation of the second row, followed by the final implementation of the third line, you might say this is not nonsense it? Wait a minute, is not always the case in the JS, for example there are three lines of code, is not at the top of the code is the first finished, is likely to be the last line of the statement was first executed, and then at the top of the line but is the last finished, so we say JS is an asynchronous programming language.

Below node.js, for example, give an example to ensure that you find out in three steps exactly what the callback function:

STEP 1:

var fs = require("fs");
var c

function f(x) {
    console.log(x)
}

function writeFile() {
    fs.writeFile('input.txt', '我是通过fs.writeFile 写入文件的内容', function (err) {
        if (!err) {
            console.log("文件写入完毕!")
            c = 1
        }
    });
}

c = 0
writeFile()
f(c)

It will be appreciated the above code, is set a global variable c = 0, then execute writeFile function (i.e. writing a file input.txt), which has the function line c = 1, the function is performed after completion jump out call f ( ) function, f () function is very simple, is to print a variable, nothing more.

In accordance with the "normal" logic of first c = 0, then call writeFile function that which has a c = 1, then call f (c), and because the call writeFile () is before f (c), so that c = 1 this statement is certainly to be executed, then the result should be printed 1, but absolutely did not expect the result turned out to be zero, obviously we we re c were assigned in writeFile function, why the result is 0 then?

Because the program runs to writeFile () When this line is a relatively time-consuming IO operations, JS encountered such action does not stay still waits until the function is finished, but a piece of code to run directly under (ie f (c)), and the result this time c = 1 line of code is actually not to be executed, so print out or 0! 

Then you would certainly say that to solve this problem is not easy, we call f (c) also put writeFile function which is not on the line chanting! This ensures recall after c = 1 f (c), right? Yes, it's that simple:

STEP 2:

var fs = require("fs");
var c

function f(x) {
    console.log(x)
}

function writeFile() { 
    fs.writeFile('input.txt', '我是通过fs.writeFile 写入文件的内容', function (err) {
        if (!err) {
            console.log("文件写入完毕!")
            c = 1
            f(c)
        }
    });
}

c = 0
writeFile() 

Logic of this code does not need to say it, because it is too simple, it is to f (c) into the writeFile () inside, then c = 1 is bound to be carried out before the implementation of f (c), not say, the result is displayed as 1. But this change is not perfect, because doing so is equivalent to f () "welded" in writeFile () again, and if I end up here want to call function is not f () function, but other other Zezheng ? Do the authors write several different writeFile (), but the difference between them is just a different function that last call? This also stupid it, so today's hero: Keyword callback debut.

STEP 3:

var fs = require("fs");

function f(x) {
    console.log(x)
}

function writeFile(callback) { //关键字callback,表示这个参数不是一个普通变量,而是一个函数
    fs.writeFile('input.txt', '我是通过fs.writeFile 写入文件的内容', function (err) {
        if (!err) {
            console.log("文件写入完毕!")
            c = 1
            callback(c) // 因为我们传进来的函数名是f(),所以此行相当于调用一次f(c)
        }
    });
}
var c = 0
writeFile(f) // 函数f作为一个参数传进writeFile函数

After the code transformation occurs twice callback keyword appears in the first callback writeFile the parameter, the act defined, indicates that this parameter is not an ordinary variable, but a function, which is the previously mentioned Key 1, the so-called "to function as a parameter." Appears in the second callback = c 1 below shows where "execute" function from the parameter passed in. As a result, writeFile () function in the end, after which the function call is finished becomes "live", and if we want writeFile () is not, as in the second example can only be called f () after the function executed, but there are other functions such as x () y () z (), you only need to write writeFile (x), writeFile (y) ... on the line.

I believe you have to see to understand the above code, because it is not profound, so we started to do in one sentence Raiders a summary:

In most programming languages, a function parameter is always from the inside to the outside is transmitted to the body of the function argument , if the parameter is the keyword in the JS "callback" is exactly the opposite, after which represents a function to perform an action in the body from the inside out calling an external function.

Sometimes, we will see the shape of some function parameter list appeared in the case of a function definition, initially feeling confused, in fact, as long as you understand the contents of the above, look at this direct embedding a function when the function is called wording will be very simple, its essence remains the callback function, because there is no function names, so also known as anonymous functions.

If as in the present embodiment to be written in this style is a long word in such a way:

var fs = require("fs");

function writeFile(callback) { 
    fs.writeFile('input.txt', '我是通过fs.writeFile 写入文件的内容', function (err) {
        if (!err) {
            console.log("文件写入完毕!")
            c = 1
            callback(c) 
        }
    });
}
var c = 0
writeFile(function (x) {
    console.log(x)
})

writeFile () function is the same, just in time to call it directly embedded in the body of the function parameter list, and its role to keep up with an example of exactly the same. In fact, in the present embodiment, the back fs.writeFile also function with an anonymous callback function (err) {}, this function represents the file when writing has been completed, it will callback, if there is an error, then the write process variable err by carrying out. I believe that with the front of the bedding, you've certainly understand its meaning, in fact, such an approach is the most common style of the mainstream in the JS.

[Supplement] in JS, of course, not all operations are asynchronous, such as the for loop, no matter how long it takes the need for loop, the system will only execute the following statement, etc. after the transfer finished it, with this most other synchronization language is the same. I know that may generate executed asynchronously about the following:

Timers, establish a network connection, network flow data is read, data is written to the file, Ajax, request the database service, and so on.

At this point, if you still can not figure out what in the end is a callback function, it is not your problem, but I must express there are deficiencies, welcome to discuss the message!

 

Ä ° ± æ¯ççä¸è¡åï¼ç "åªï¼

 

Guess you like

Origin blog.csdn.net/rockage/article/details/79513450