Create a custom callback in JavaScript

前端 未结 10 2169
野性不改
野性不改 2020-11-22 08:08

All I need to do is to execute a callback function when my current function execution ends.

function LoadData() 
{
    alert(\'The data has been loaded\');
          


        
相关标签:
10条回答
  • 2020-11-22 08:42

    Some of the answers, while correct may be a little tricky to understand. Here is an example in layman's terms:

    var users = ["Sam", "Ellie", "Bernie"];
    
    function addUser(username, callback)
    {
        setTimeout(function()
        {
            users.push(username);
            callback();
        }, 200);
    }
    
    function getUsers()
    {
        setTimeout(function()
        {
            console.log(users);
        }, 100);
    }
    
    addUser("Jake", getUsers);
    

    The callback means, "Jake" is always added to the users before displaying the list of users with console.log.

    Source (YouTube)

    0 讨论(0)
  • 2020-11-22 08:44

    It is good practice to make sure the callback is an actual function before attempting to execute it:

    if (callback && typeof(callback) === "function") {
    
      callback();
    }
    
    0 讨论(0)
  • 2020-11-22 08:46
       function callback(e){
          return e;
       }
        var MyClass = {
           method: function(args, callback){
              console.log(args);
              if(typeof callback == "function")
              callback();
           }    
        }
    

    ==============================================

    MyClass.method("hello",function(){
        console.log("world !");
    });
    

    ==============================================

    Result is:

    hello world !
    
    0 讨论(0)
  • 2020-11-22 08:54
    function loadData(callback) {
    
        //execute other requirement
    
        if(callback && typeof callback == "function"){
            callback();
       }
    }
    
    loadData(function(){
    
       //execute callback
    
    });
    
    0 讨论(0)
  • 2020-11-22 08:59

    Actually, your code will pretty much work as is, just declare your callback as an argument and you can call it directly using the argument name.

    The basics

    function doSomething(callback) {
        // ...
    
        // Call the callback
        callback('stuff', 'goes', 'here');
    }
    
    function foo(a, b, c) {
        // I'm the callback
        alert(a + " " + b + " " + c);
    }
    
    doSomething(foo);
    

    That will call doSomething, which will call foo, which will alert "stuff goes here".

    Note that it's very important to pass the function reference (foo), rather than calling the function and passing its result (foo()). In your question, you do it properly, but it's just worth pointing out because it's a common error.

    More advanced stuff

    Sometimes you want to call the callback so it sees a specific value for this. You can easily do that with the JavaScript call function:

    function Thing(name) {
        this.name = name;
    }
    Thing.prototype.doSomething = function(callback) {
        // Call our callback, but using our own instance as the context
        callback.call(this);
    }
    
    function foo() {
        alert(this.name);
    }
    
    var t = new Thing('Joe');
    t.doSomething(foo);  // Alerts "Joe" via `foo`
    

    You can also pass arguments:

    function Thing(name) {
        this.name = name;
    }
    Thing.prototype.doSomething = function(callback, salutation) {
        // Call our callback, but using our own instance as the context
        callback.call(this, salutation);
    }
    
    function foo(salutation) {
        alert(salutation + " " + this.name);
    }
    
    var t = new Thing('Joe');
    t.doSomething(foo, 'Hi');  // Alerts "Hi Joe" via `foo`
    

    Sometimes it's useful to pass the arguments you want to give the callback as an array, rather than individually. You can use apply to do that:

    function Thing(name) {
        this.name = name;
    }
    Thing.prototype.doSomething = function(callback) {
        // Call our callback, but using our own instance as the context
        callback.apply(this, ['Hi', 3, 2, 1]);
    }
    
    function foo(salutation, three, two, one) {
        alert(salutation + " " + this.name + " - " + three + " " + two + " " + one);
    }
    
    var t = new Thing('Joe');
    t.doSomething(foo);  // Alerts "Hi Joe - 3 2 1" via `foo`
    
    0 讨论(0)
  • 2020-11-22 09:00

    When calling the callback function, we could use it like below:

    consumingFunction(callbackFunctionName)

    Example:

    // Callback function only know the action,
    // but don't know what's the data.
    function callbackFunction(unknown) {
      console.log(unknown);
    }
    
    // This is a consuming function.
    function getInfo(thenCallback) {
      // When we define the function we only know the data but not
      // the action. The action will be deferred until excecuting.
      var info = 'I know now';
      if (typeof thenCallback === 'function') {
        thenCallback(info);    
      }
    }
    
    // Start.
    getInfo(callbackFunction); // I know now
    

    This is the Codepend with full example.

    0 讨论(0)
提交回复
热议问题