How to explain callbacks in plain english? How are

2018-12-31 17: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 their power be explained to a novice programmer?

30条回答
美炸的是我
2楼-- · 2018-12-31 17:20

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.

查看更多
素衣白纱
3楼-- · 2018-12-31 17:21

A callback is a function that will be called by a second function. This second function doesn't know in advance what function it will call. So the identity of the callback function is stored somewhere, or passed to the second function as a parameter. This "identity," depending on the programming language, might be the address of the callback, or some other sort of pointer, or it might be the name of the function. The principal is the same, we store or pass some information that unambiguously identifies the function.

When the time comes, the second function can call the callback, supplying parameters depending on the circumstances at that moment. It might even choose the callback from a set of possible callbacks. The programming language must provide some kind of syntax to allow the second function to call the callback, knowing its "identity."

This mechanism has a great many possible uses. With callbacks, the designer of a function can let it be customized by having it call whatever callbacks are provided. For example, a sorting function might take a callback as a parameter, and this callback might be a function for comparing two elements to decide which one comes first.

By the way, depending on the programming language, the word "function" in the above discussion might be replaced by "block," "closure," "lambda," etc.

查看更多
若你有天会懂
4楼-- · 2018-12-31 17:23

How to explain callbacks in plain English?

In plain English, a callback function is like a Worker who "calls back" to his Manager when he has completed a Task.

How are they different from calling one function from another function taking some context from the calling function?

It is true that you are calling a function from another function, but the key is that the callback is treated like an Object, so you can change which Function to call based on the state of the system (like the Strategy Design Pattern).

How can their power be explained to a novice programmer?

The power of callbacks can easily be seen in AJAX-style websites which need to pull data from a server. Downloading the new data may take some time. Without callbacks, your entire User Interface would "freeze up" while downloading the new data, or you would need to refresh the entire page rather than just part of it. With a callback, you can insert a "now loading" image and replace it with the new data once it is loaded.

Some code without a callback:

function grabAndFreeze() {
    showNowLoading(true);
    var jsondata = getData('http://yourserver.com/data/messages.json');
    /* User Interface 'freezes' while getting data */
    processData(jsondata);
    showNowLoading(false);
    do_other_stuff(); // not called until data fully downloaded
}

function processData(jsondata) { // do something with the data
   var count = jsondata.results ? jsondata.results.length : 0;
   $('#counter_messages').text(['Fetched', count, 'new items'].join(' '));
   $('#results_messages').html(jsondata.results || '(no new messages)');
}

With Callback:

Here is an example with a callback, using jQuery's getJSON:

function processDataCB(jsondata) { // callback: update UI with results
   showNowLoading(false);
   var count = jsondata.results ? jsondata.results.length : 0;
   $('#counter_messages').text(['Fetched', count, 'new items'].join(' '));
   $('#results_messages').html(jsondata.results || '(no new messages)');
}

function grabAndGo() { // and don't freeze
    showNowLoading(true);
    $('#results_messages').html(now_loading_image);
    $.getJSON("http://yourserver.com/data/messages.json", processDataCB);
    /* Call processDataCB when data is downloaded, no frozen User Interface! */
    do_other_stuff(); // called immediately
}

With Closure:

Often the callback needs to access state from the calling function using a closure, which is like the Worker needing to get information from the Manager before he can complete his Task. To create the closure, you can inline the function so it sees the data in the calling context:

/* Grab messages, chat users, etc by changing dtable. Run callback cb when done.*/
function grab(dtable, cb) { 
    if (null == dtable) { dtable = "messages"; }
    var uiElem = "_" + dtable;
    showNowLoading(true, dtable);
    $('#results' + uiElem).html(now_loading_image);
    $.getJSON("http://yourserver.com/user/"+dtable+".json", cb || function (jsondata) {
       // Using a closure: can "see" dtable argument and uiElem variables above.
       var count = jsondata.results ? jsondata.results.length : 0, 
           counterMsg = ['Fetched', count, 'new', dtable].join(' '),
           // no new chatters/messages/etc
           defaultResultsMsg = ['(no new ', dtable, ')'].join(''); 
       showNowLoading(false, dtable);
       $('#counter' + uiElem).text(counterMsg);
       $('#results'+ uiElem).html(jsondata.results || defaultResultsMsg);
    });
    /* User Interface calls cb when data is downloaded */

    do_other_stuff(); // called immediately
}

Usage:

// update results_chatters when chatters.json data is downloaded:
grab("chatters"); 
// update results_messages when messages.json data is downloaded
grab("messages"); 
// call myCallback(jsondata) when "history.json" data is loaded:
grab("history", myCallback); 

Closure

Finally, here is a definition of closure from Douglas Crockford:

Functions can be defined inside of other functions. The inner function has access to the vars and parameters of the outer function. If a reference to an inner function survives (for example, as a callback function), the outer function's vars also survive.

See also:

查看更多
浅入江南
5楼-- · 2018-12-31 17:23

In non-programmer terms, a callback is a fill-in-the-blank in a program.

A common item on many paper forms is "Person to call in case of emergency". There is a blank line there. You write in someone's name and phone number. If an emergency occurs, then that person gets called.

  • Everyone gets the same blank form, but
  • Everyone can write a different emergency contact number.

This is key. You do not change the form (the code, usually someone else's). However you can fill in missing pieces of information (your number).

Example 1:

Callbacks are used as customized methods, possibly for adding to/changing a program's behavior. For example, take some C code that performs a function, but does not know how to print output. All it can do is make a string. When it tries to figure out what to do with the string, it sees a blank line. But, the programmer gave you the blank to write your callback in!

In this example, you do not use a pencil to fill in a blank on a sheet of paper, you use the function set_print_callback(the_callback).

  • The blank variable in the module/code is the blank line,
  • set_print_callback is the pencil,
  • and the_callback is your information you are filling in.

You've now filled in this blank line in the program. Whenever it needs to print output, it will look at that blank line, and follow the instructions there (i.e. call the function you put there.) Practically, this allows the possibility of printing to screen, to a log file, to a printer, over a network connection, or any combination thereof. You have filled in the blank with what you want to do.

Example 2:

When you get told you need to call an emergency number, you go and read what is written on the paper form, and then call the number you read. If that line is blank nothing will be done.

Gui programming works much the same way. When a button is clicked, the program needs to figure out what to do next. It goes and looks for the callback. This callback happens to be in a blank labeled "Here's what you do when Button1 is clicked"

Most IDEs will automatically fill in the blank for you (write the basic method) when you ask it to (e.g. button1_clicked). However that blank can have any method you darn well please. You could call the method run_computations or butter_the_biscuits as long as you put that callback's name in the proper blank. You could put "555-555-1212" in the emergency number blank. It doesn't make much sense, but it's permissible.


Final note: That blank line that you're filling in with the callback? It can be erased and re-written at will. (whether you should or not is another question, but that is a part of their power)

查看更多
宁负流年不负卿
6楼-- · 2018-12-31 17:23

Let's pretend you were to give me a potentially long-running task: get the names of the first five unique people you come across. This might take days if I'm in a sparsely populated area. You're not really interested in sitting on your hands while I'm running around so you say, "When you've got the list, call me on my cell and read it back to me. Here's the number.".

You've given me a callback reference--a function that I'm supposed to execute in order to hand off further processing.

In JavaScript it might look something like this:

var lottoNumbers = [];
var callback = function(theNames) {
  for (var i=0; i<theNames.length; i++) {
    lottoNumbers.push(theNames[i].length);
  }
};

db.executeQuery("SELECT name " +
                "FROM tblEveryOneInTheWholeWorld " +
                "ORDER BY proximity DESC " +
                "LIMIT 5", callback);

while (lottoNumbers.length < 5) {
  playGolf();
}
playLotto(lottoNumbers);

This could probably be improved in lots of ways. E.g., you could provide a second callback: if it ends up taking longer than an hour, call the red phone and tell the person that answers that you've timed out.

查看更多
余生请多指教
7楼-- · 2018-12-31 17:23

What Is a Callback Function?

The simple answer to this first question is that a callback function is a function that is called through a function pointer. If you pass the pointer (address) of a function as an argument to another, when that pointer is used to call the function it points to it is said that a call back is made.

Callback function is hard to trace, but sometimes it is very useful. Especially when you are designing libraries. Callback function is like asking your user to gives you a function name, and you will call that function under certain condition.

For example, you write a callback timer. It allows you to specified the duration and what function to call, and the function will be callback accordingly. “Run myfunction() every 10 seconds for 5 times”

Or you can create a function directory, passing a list of function name and ask the library to callback accordingly. “Callback success() if success, callback fail() if failed.”

Lets look at a simple function pointer example

void cbfunc()
{
     printf("called");
}

 int main ()
 {
                   /* function pointer */ 
      void (*callback)(void); 
                   /* point to your callback function */ 
      callback=(void *)cbfunc; 
                   /* perform callback */
      callback();
      return 0; 
}

How to pass argument to callback function?

Observered that function pointer to implement callback takes in void *, which indicates that it can takes in any type of variable including structure. Therefore you can pass in multiple arguments by structure.

typedef struct myst
{
     int a;
     char b[10];
}myst;

void cbfunc(myst *mt) 
{
     fprintf(stdout,"called %d %s.",mt->a,mt->b); 
}

int main() 
{
       /* func pointer */
    void (*callback)(void *);       //param
     myst m;
     m.a=10;
     strcpy(m.b,"123");       
     callback = (void*)cbfunc;    /* point to callback function */
     callback(&m);                /* perform callback and pass in the param */
     return 0;   
}
查看更多
登录 后发表回答