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

后端 未结 30 1575
时光说笑
时光说笑 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:33

    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

    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.

提交回复
热议问题