ChApter 1 ■ JAvASCrIpt You Need to KNow
Listing 1-32 is a little contrived, but it shows the general idea of how callbacks work.
Listing 1-32. A Simple Callback in Action
<!DOCTYPE html>
Here we have a variable called actionsToTakeWhenServerHasResponded. This variable is a function reference.
On the next line down, we have a function called communicateWithServer. The thing to take note of here is that this
function takes an argument, which we have named callback, which it expects to be a function reference.
Finally, on the last line, we call the communicateWithServer function and pass it the
actionsToTakeWhenServerHasResponded variable. I hope that you can see that inside our communicateWithServer
function, our actionsToTakeWhenServerHasResponded function is executed through the callback reference. See the
following results:
The server just responded!
For the most part, this example represents the nature of callbacks. One thing it doesn’t do very well is
demonstrate time passing as the communicateWithServer does some presumably lengthy task. This is really the point
of callbacks—your program can continue to execute as opposed to sitting idle waiting for some lengthy process to
finish. Here is a code snippet that shows how this might look in action:
console.log('1')
$http.post('/ http://someurl.com/someService ', data).success(function () {
console.log('2')
});
console.log('3')