Object and can be referenced like any other first-class object, such as
So what does this mean? Since functions are actually objects, they can be assigned to variables and passed as arguments to functions.
For example, take a look at the following snippet.
The result might be what you expect.
Back at it again!
Now let’s add a timeout to the first function.
After a three second delay, this gets outputted:
Back at it again!
setTimeout, which queues an operation to run after a certain delay (in this case, after 3 seconds). The concept of running after a certain time is exactly what asynchronous means.
Now, for obvious reasons, we want the text
Back at it again! to show after
Damn Daniel. To do so, we can store
functionSecond() as a callback.
Back at it again
with the white Vans!
We can see that
functionSecond as an argument, or callback, and this means that
functionFirst is a higher-order function. In other words,
functionFirst will call the second function back later once its operation is complete.
So why is this useful? Say you send off an HTTP request and you need to do something with the response. Instead of holding up your browser, you can use a callback to handle the response whenever it arrives. Another useful example in this context could be when your application is dependent on user input.
The only reason I used
setTimeout was to simulate an operation that takes a certain time. Such operations could be reading from a text file, downloading things or performing an HTTP request. Node, for example, is built entirely on an asynchronous concept and uses callbacks extensively. The following is a simple example.
Notice the first argument of the call back is reserved for an error object. This is the error callback convention that has been standardized to allow for Node’s asynchronous nature.
Wrapping things up