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

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

    Imagine you need a function that returns 10 squared so you write a function:

    function tenSquared() {return 10*10;}
    

    Later you need 9 squared so you write another function:

    function nineSquared() {return 9*9;}
    

    Eventually you will replace all of these with a generic function:

    function square(x) {return x*x;}
    

    The exact same thinking applies for callbacks. You have a function that does something and when done calls doA:

    function computeA(){
        ...
        doA(result);
    }
    

    Later you want the exact same function to call doB instead you could duplicate the whole function:

    function computeB(){
        ...
        doB(result);
    }
    

    Or you could pass a callback function as a variable and only have to have the function once:

    function compute(callback){
        ...
        callback(result);
    }
    

    Then you just have to call compute(doA) and compute(doB).

    Beyond simplifying code, it lets asynchronous code let you know it has completed by calling your arbitrary function on completion, similar to when you call someone on the phone and leave a callback number.

提交回复
热议问题