Could someone explain, why do we use callback in JavaScript? I found examples, but they could be implemented by using the normal functions. What is the advantage of using it? I got answers to "how" to use it and not "why and when" do we need to use it.
Typically, I found it being used in AJAX. on the httpRequest.onreadystatechange
. Is this similar to Java's multi-threading? How and where is the listener for the response?
Is asyncronous programming akin to multi-threading?
In the following code, how is the flow of control:
function some_function(arg1, arg2, callback) {
var my_number = Math.ceil(Math.random() * (arg1 - arg2) + arg2);
callback(my_number);
some_different_function_not_callback(arg1);
}
some_function(5, 15, function(num) {
console.log("callback called! " + num);
});
From the JQuery website:
The special thing about a callback is that functions that appear after the "parent" can execute before the callback executes" (ref: http://docs.jquery.com/Tutorials:How_jQuery_Works)
Could someone explain me this line with an example?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…