Usefulness of callback functions

后端 未结 5 886
鱼传尺愫
鱼传尺愫 2021-01-18 11:04

In Javascript there is a possibility to define a function X and pass it as an argument to another function Y.

Such a function X is called a callback function

5条回答
  •  生来不讨喜
    2021-01-18 11:15

    In JavaScript, a great deal of function calls are asynchronous (for instance using XMLHTTPRequest to perform AJAX requests). As such, you don't know when the return value will arrive, as your browser us executing something else in the background.

    Without causing the rest of your script to stop running, the notion of a callback function allows you to run a procedure as soon as an asynchronous call has finished performing what it needs to do.

    For instance, suppose I'm requesting foo.json from somewhere. I would do something like (fictional code):

    ajaxGet("foo.json", function(data)
    {
        doSomethingWith(data);
    });
    doSomethingElse();
    

    The callback function will (function(data) { ... }) will execute of its own accord when ajaxGet has retrieved the data and is now ready. Before that, doSomethingElse() will execute and not hang the browser.


    To answer your question regarding other JavaScript environments, let's look at node.js, arguably the most popular one there is.

    Now, node.js is fully asynchronous, meaning that function calls never block (theoretically) and therefore you're going to have to have callbacks that call callbacks for performing any kind of asynchronous I/O. In fact, I would say node.js is almost bona fide continuation-passing style, where functions don't return and rely on callbacks to pass their values forward.

提交回复
热议问题