How exactly callbacks get their arguments?

大城市里の小女人 提交于 2019-12-02 16:26:48

问题


I have trouble understanding how callbacks in JavaScript get their arguments. Or in other words: how to implement a higher-order function so its callback accepts for instance a standard err and data arguments.

Like in this article on asynchronous JavaScript in the example of a callback used in a usual way (and I know it's usual because I see exactly this pattern used in Node.js moongose (i.e. for creating data in db)):

function getData(options, callback) { 
    $.get("example.php", options, function(response) { 
        callback(null, JSON.parse(response)); 
    }, function() { 
        callback(new Error("AJAX request failed!")); 
    }); 
} 

// usage 
getData({name: "John"}, function(err, data) { 
    if(err) { 
        console.log("Error! " + err.toString()) 
    } else { 
        console.log(data); 
    } 
});

how exactly the callback gets arguments err & data based on how getData() function is declared above?


回答1:


Arguments are passed to a function when that function is called.

function foo(arg) {
    console.log(arg);
}

foo("This is the value");

This is still true when it is a callback function.

function foo(arg) {
    console.log(arg);
}

function bar(callback) {
    callback("This is the value");
}

bar(foo);

And it is still true when the callback function is called by code written by someone else that exists in a library you aren't examining the source code of.



来源:https://stackoverflow.com/questions/46931121/how-exactly-callbacks-get-their-arguments

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!