Usefulness of callback functions

后端 未结 5 946
鱼传尺愫
鱼传尺愫 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条回答
  •  Happy的楠姐
    2021-01-18 11:18

    Callbacks are highly popular in JavaScript since AJAX. AJAX is asynchonous call to another Web resouce, since you don't know when it is going to be finished, application don't need to wait for response. Instead, it continues exectution and you provide a callback to be called as soon as request is done.

    This simple code provides callback, to show the products retrieved from server:

    $.get('/service/products', function(p) {
       alert(p);
    });
    

    Moreover, due to JavaScript is functional language by nature functions have major role here. You are passing functions to functions, or returning functions from function. It is very useful for different patterns implementations, like

    function getPersonFactory(name) {
       var create = function () {
          return new Person(name);
       }
    
       return create;
    }
    
    var factory = getPersonFactory('Joe');
    var person = factory();
    

    Because of JavaScript functional nature and goog-looking and easy callback programming it found its implications for frameworks like Node.js, which is javascript framework highly optimized on IO operations.

    Node.js HelloWorld:

    var http = require("http");
    
    http.createServer(function(request, response) {
      response.writeHead(200, {"Content-Type": "text/plain"});
      response.write("Hello World");
      response.end();
    }).listen(8888);
    

    See, it creates HTTP server and provide callback for each request comming to that server. You will out the response and ends it. Very compact and efficient code.

    For hardcore functional programming you might take a look this great article:

    http://matt.might.net/articles/implementation-of-recursive-fixed-point-y-combinator-in-javascript-for-memoization/

提交回复
热议问题