and leave the rest in the past. It’s not that simple, though. Generators by themselves
do not provide any sort of asynchronous support: they rely on either promises or a
special type of callback to provide asynchronous behavior. Likewise, as useful as
promises are, they rely on callbacks (and callbacks by themselves are still useful for
things like events).
Aside from user input, the three primary things you’ll be using asynchronous techni‐
ques for are:
• Network requests (Ajax calls, for instance)
• Filesystem operations (reading/writing files, etc.)
• Intentionally time-delayed functionality (an alarm, for example)
The Analogy
The analogy I like to use for both callbacks and promises is getting a table at a busy
restaurant when you don’t have a reservation. So you don’t have to wait in line, one
restaurant will take your mobile phone number and call you when your table is ready.
This is like a callback: you’ve provided the host with something that allows them to
let you know when your table is ready. The restaurant is busy doing things, and you
can busy yourself with other things; nobody’s waiting on anyone else. Another restau‐
rant might give you a pager that will buzz when your table is ready. This is more like a
promise: something the host gives to you that will let you know when your table is
ready.
As we move through callbacks and promises, keep these analogies in mind, especially
if you are new to asynchronous programming.
Callbacks
Callbacks are the oldest asynchronous mechanism in JavaScript, and we’ve already
seen them used to handle user input and timeouts. A callback is simply a function
that you write that will be invoked at some point in the future. There’s nothing special
about the function itself: it’s just a regular JavaScript function. Typically, you provide
these callback functions to other functions, or set them as properties on objects (or,
rarely, provide them in an array). Callbacks are very often (but not always) anony‐
mous functions.
Let’s start with a simple example, using
setTimeout
, a built-in function that delays
execution some number of milliseconds:
console
.
log
(
"Before timeout: "
+
new
Date
());
function
f
() {
console
.
log
(
"After timeout: "
+
new
Date
());
200 | Chapter 14: Asynchronous Programming