[removed] How does a callback function work?

前端 未结 5 837
伪装坚强ぢ
伪装坚强ぢ 2020-12-12 08:16

I\'m really new to JS and I\'m having a lot of trouble writing/understanding callback functions Let\'s say for example, I have the following code, but i dont want



        
5条回答
  •  天涯浪人
    2020-12-12 09:02

    The basics (not about callbacks, but about programming languages)

    To understand callbacks first you have to understand functions. And to understand functions in javascript you first have to understand variables, values and functions.

    Almost all programming language can deal with values. So if you've done any programming you'd have a basic idea of what values are (I'm going to greatly simplify types of values here and refer to both values and references/pointers as "values").

    A value is a thing. For example a number or a string. So 22.31 is a value and "Hello Dave" is a value.

    Most languages also have the concept of variables (not all do though). A variable is a "name" we give to values to make it easier to process values. For example, in the following, x is a variable:

    var x = 12;
    

    .. and it's value is 12.

    What do variables allow us to do? It allows us to substitute a value for a name in our calculations. Just like math. For example, if x is 12 and we know we can add 1 to 12 we can also do:

    x + 1
    

    Functions are values

    In javascript functions are values. For example, in the following we assign a function to a variable:

    function a () {return "Hello"}
    var y = a;
    

    Since what variables do is to allow you to substitute a name for a value then if you can call the function a using the syntax a() it means you can also do this with the variable y:

    y(); // returns "Hello"
    

    Callbacks

    If functions are values it also means that you can pass functions as arguments to other functions. For example, the following is how you'd normally call a function in another function:

    function a () {return "Hello"}
    
    function b () {return a() + " World"}
    
    b(); // returns "Hello World"
    

    If you can pass functions as a variable, it means you can do something like this:

    function a () {return "Hello"}
    function b () {return "Bye"}
    
    function c (functionVariable) {return functionVariable() + " World"}
    
    c(a); // returns "Hello World"
    c(b); // returns "Bye World"
    

    As you can see. Callbacks are not special at all. They're just the result of the fact that in javascript functions obey the same rules as other values like numbers, arrays and strings.

    Callbacks does not mean asynchronous

    As you can see from the example above, both calls to the function c return a value. Thus the function c is not asynchronous even though it accepts a callback. So callbacks can be used for both synchronous and asynchronous code.

    A good example of a synchronous callback is the Array.sort() method. It sorts an array but accepts an optional callback for you to define how to sort (alphabetically, numerically, by last name etc.).

    Why asynchronous code need callbacks

    For now forget about ajax or networking code. Let's instead look at a scenario that makes it even more obvious why callbacks are used by asynchronous code.

    Say for example you have a button. Now, when the user click this button you want something to happen. How do you do that?

    The first thing most people do is probably something like this:

    while (1) {
        if (button.isClicked) {
            doSomething();
        }
    }
    

    OK. So that's an infinite loop that only checks if the button is clicked and nothing else. Then how do you expect the browser to update the UI and track the mouse? This leads us to the next thing people try to do:

    while (1) {
        if (button.isClicked) {
            doSomething();
        }
        else {
            updateUI();
        }
    }
    

    OK. Great. But two problems. First, if someone were to write a library like Google Charts or jQuery or anything to do with the UI they either will write their own while(1)... loop or you must manually copy/paste their function into your while loop. This does not scale. Second and more importantly, this is inefficient. That while loop will use 100% CPU time checking a button. Wouldn't it be nicer if the browser can tell us when the button is clicked.

    Fortunately in javascript functions are just values. You can pass a function to the browser and tell it to execute your function when someone clicks a button:

    button.addEventListener('click', doSomething);
    

    Note: Notice the difference between treating a function as a variable and calling a function. If you want to treat a function as a variable just use the name. If you want to call a function use braces like doSomething().

    Why everyone insist on writing asynchronous functions

    There are two reasons why everyone seem to insist on making asynchronous APIs, especially in languages like javascript.

    First, the low-level file and network I/O are async. This means that if you want to talk to a database or a server or read a file you need to implement it as asynchronous. Also, javascript is single threaded. So if you use the synchronous versions of I/O functions you will freeze everything else.

    Second, it turns out that in a lot of cases (but certainly not in all) asynchronous, single-threaded programming is as fast as or sometimes even faster than synchronous multi-threaded programming.

    Combined, the two reasons above creates social pressure in the js community to ensure that all I/O code are asynchronous in order to maintain the speed advantage and not block other people's code.

提交回复
热议问题