Why use callback in JavaScript, what are its advantages?

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?


The main browser process is a single threaded event loop. If you execute a long-running operation within a single-threaded event loop, the process "blocks". This is bad because the process stops processing other events while waiting for your operation to complete. 'alert' is one of the few blocking browser methods: if you call alert('test'), you can no longer click links, perform ajax queries, or interact with the browser UI.

In order to prevent blocking on long-running operations, the XMLHttpRequest provides an asynchronous interface. You pass it a callback to run after the operation is complete, and while it is processing it cedes control back to the main event loop instead of blocking.

There's no reason to use a callback unless you want to bind something to an event handler, or your operation is potentially blocking and therefore requires an asynchronous programming interface.

This is an excellent video discussing more about the event loop used in the browser, as well as on the server side in node.js.

EDIT: that convoluted line from the jQuery documentation just means that the callback executes asynchronously as control is ceded back to the main event loop.

parent_function(function () { console.log('Callback'); });
parent_doesnt_block(); // <-- function appears after "parent"
therefore_execution_continues();
// Maybe we get 'Callback' in the console here? or maybe later...
execution_still_continues();

Not quite like multithreading...

You use a callback anytime you need to wait on something external to your primary JS code. In a browser this is used a ton for AJAX, and in node.js it's used for every single thing that calls out to the system (file access, networks access, database requests, etc).

Let's say you want to fire an ajax request everytime a user clicks a button. Now lets say that ajax request takes 10 seconds to complete. The user then clicks 10 of these buttons before those 10 seconds are up. This would repeatedly call a function like this:

var clicked = function() {
  doAjax('/some/path.json', function(result) {
    updatePageWith(result.widgets);
  });
};

This runs code in the JS engine for only long enough to make the request. Then it idles while it waits. Other JS can run at this point, the UI is totally fluid and interactive, everything is awesome. Then suddenly, all 10 of those requests resolve at once. And then our callback is invoked 10 times like magic.

This works because every time we call clicked() we are creating a new function object, and passing it to the doAjax() function. So there are 10 unique callback function objects hanging out in memory, each one bound to a specific request by the doAjax() function. When a request returns, it finds the associated callback object and calls it.

The huge advantage here is that, although javascript is single threaded, you never tie up that thread with waiting. If you JS thread is busy, it should only ever be because it's actively running code. So even though JS is single threaded, it's trivial for your code to implicitly hold the state of any number of any kind of asynchronous tasks.

The synchronous method of callbacks are used for a different purpose usually. Like listeners or delegates. Like telling object A to callback when it's data changes. While not strictly asynchronous, you usually aren't calling that callback immediately. Instead it will be called later in response to some sort of user action of event.


Because the javascript being executed is Asynchronous, therefore if you just put any old function after making the asynchronous request, it will likely be called before the original request completes. The original request will return as soon as it BEGINS (is sent out), not completes.

If you need to do something with the result of the asynchronous request, or chain together requests, etc you will need a callback to ensure the next step doesn't begin before the previous step is finished.

链接地址: http://www.djcxy.com/p/80510.html

上一篇: 如何修改函数中的数组?

下一篇: 为什么在JavaScript中使用回调,它的优点是什么?