How to explain callbacks in plain english? How are they different from calling one function from another function?

后端 未结 30 1539
时光说笑
时光说笑 2020-11-22 11:13

How to explain callbacks in plain English? How are they different from calling one function from another function taking some context from the calling function? How can thei

相关标签:
30条回答
  • 2020-11-22 11:17

    I'm stunned to see so many intelligent people failing to stress the reality that the word "callback" has come to be used in two inconsistent ways.

    Both ways involve the customization of a function by passing additional functionality (a function definition, anonymous or named) to an existing function. ie.

    customizableFunc(customFunctionality)
    

    If the custom functionality is simply plugged into the code block, you have customized the function, like so.

        customizableFucn(customFunctionality) {
          var data = doSomthing();
          customFunctionality(data);
          ...
        }
    

    Though this kind of injected functionality is often called a "callback", there is nothing contingent about it. A very obvious example is the forEach method in which a custom function is supplied as an argument to be applied to each element in an array to modify the array.

    But this is fundamentally distinct from the use of "callback" functions for asynchronous programming, as in AJAX or node.js or simply in assigning functionality to user interaction events (like mouse clicks). In this case, the whole idea is to wait for a contingent event to occur before executing the custom functionality. This is obvious in the case of user interaction, but is also important in i/o (input/output) processes that can take time, like reading files from disk. This is where the term "callback" makes the most obvious sense. Once an i/o process is started (like asking for a file to be read from disk or a server to return data from an http request) an asynchronous program doesn't wait around for it to finish. It can go ahead with whatever tasks are scheduled next, and only respond with the custom functionality after it has been notified that the read file or http request is completed (or that it failed) and that the data is available to the custom functionality. It's like calling a business on the phone and leaving your "callback" number, so they can call you when someone is available to get back to you. That's better than hanging on the line for who knows how long and not being able to attend to other affairs.

    Asynchronous use inherently involves some means of listening for the desired event (e.g, the completion of the i/o process) so that, when it occurs (and only when it occurs) the custom "callback" functionality is executed. In the obvious AJAX example, when the data actually arrives from the server, the "callback" function is triggered to use that data to modify the DOM and therefore redraw the browser window to that extent.

    To recap. Some people use the word "callback" to refer to any kind of custom functionality that can be injected into an existing function as an argument. But, at least to me, the most appropriate use of the word is where the injected "callback" function is used asynchronously -- to be executed only upon the occurrence of an event that it is waiting to be notified of.

    0 讨论(0)
  • 2020-11-22 11:18

    Johny the programmer needs a stapler, so he goes down to the office supply department and ask for one, after filling the request form he can either stand there and wait for the clerk go look around the warehouse for the stapler (like a blocking function call) or go do something else meantime.

    since this usually takes time, johny puts a note together with the request form asking them to call him when the stapler is ready for pickup, so meantime he can go do something else like napping on his desk.

    0 讨论(0)
  • 2020-11-22 11:18

    You feel ill so you go to the doctor. He examines you and determines you need some medication. He prescribes some meds and calls the prescription into your local pharmacy. You go home. Later your pharmacy calls to tell you your prescription is ready. You go and pick it up.

    0 讨论(0)
  • 2020-11-22 11:19

    Imagine a friend is leaving your house, and you tell her "Call me when you get home so that I know you arrived safely"; that is (literally) a call back. That's what a callback function is, regardless of language. You want some procedure to pass control back to you when it has completed some task, so you give it a function to use to call back to you.

    In Python, for example,

    grabDBValue( (lambda x: passValueToGUIWindow(x) ))
    

    grabDBValue could be written to only grab a value from a database and then let you specify what to actually do with the value, so it accepts a function. You don't know when or if grabDBValue will return, but if/when it does, you know what you want it to do. Here, I pass in an anonymous function (or lambda) that sends the value to a GUI window. I could easily change the behavior of the program by doing this:

    grabDBValue( (lambda x: passToLogger(x) ))
    

    Callbacks work well in languages where functions are first class values, just like the usual integers, character strings, booleans, etc. In C, you can "pass" a function around by passing around a pointer to it and the caller can use that; in Java, the caller will ask for a static class of a certain type with a certain method name since there are no functions ("methods," really) outside of classes; and in most other dynamic languages you can just pass a function with simple syntax.

    Protip:

    In languages with lexical scoping (like Scheme or Perl) you can pull a trick like this:

    my $var = 2;
    my $val = someCallerBackFunction(sub callback { return $var * 3; });
    # Perlistas note: I know the sub doesn't need a name, this is for illustration
    

    $val in this case will be 6 because the callback has access to the variables declared in the lexical environment where it was defined. Lexical scope and anonymous callbacks are a powerful combination warranting further study for the novice programmer.

    0 讨论(0)
  • 2020-11-22 11:21

    This of it in terms of downloading a webpage:

    Your program runs on a cellphone and is requesting the webpage http://www.google.com. If you write your program synchronously, the function you write to download the data will be running continuously until all the data is download. This means your UI will not refresh and will basically appear frozen. If you write your program using callbacks, you request the data and say "execute this function when you've finished." This allows the UI to still allow user interaction while the file is downloading. Once the webpage has finished downloading, your result function (callback) is called and you can handle the data.

    Basically, it allows you to request something and continue executing while waiting for the result. Once the result comes back to you via a callback function, you can pick up the operation where it left off.

    0 讨论(0)
  • 2020-11-22 11:22

    Without callback neither others special programming resources (like threading, and others), a program is exactly a sequence of instructions which are executed sequentially one after the other, and even with a kind of "dynamic behavior" determined by certain conditions, all possible scenarios shall be previously programmed.

    So, If we need to provide a real dynamic behavior to a program we can use callback. With callback you can instructs by parameters, a program to call an another program providing some previously defined parameters and can expects some results (this is the contract or operation signature), so these results can be produced/processed by third-party program which wasn't previously known.

    This technique is the foundation of polymorphism applied to programs, functions, objects and all others unities of code ran by computers.

    The human world used as example to callback is nice explained when you are doing some job, lets suppose you are a painter (here you are the main program, that paints) and call your client sometimes to ask him to approve the result of your job, so, he decides if the picture is good (your client is the third-party program).

    In the above example you are a painter and "delegate" to others the job to approve the result, the picture is the parameter, and each new client (the called-back "function") changes the result of your work deciding what he wants about the picture (the decision made by the clients are the returned result from the "callback function").

    I hope this explanation can be useful.

    0 讨论(0)
提交回复
热议问题