CHAPTER 14
Asynchronous Programming
We got a hint of asynchronous programming in
when we responded to
user interaction. Recall that user interaction is naturally asynchronous: you can’t con‐
trol when a user clicks, touches, speaks, or types. But user input isn’t the only reason
for asynchronous execution: the very nature of JavaScript makes it necessary for
many things.
When a JavaScript application runs, it runs single-threaded. That is, JavaScript only
ever does one thing at a time. Most modern computers are capable of doing multiple
things at once (assuming they have multiple cores), and even computers with a single
core are so fast that they can simulate doing multiple things at once by doing a tiny
bit of task A, then a tiny bit of task B, then a tiny bit of task C, and so on until all the
tasks are done (this is called preemptive multitasking). From the user’s perspective,
tasks A, B, and C ran simultaneously, whether or not the tasks were actually running
simultaneously on multiple cores.
So JavaScript’s single-threaded nature might strike you as a limiting factor, but it
actually frees you from having to worry about some very thorny problems that are
present in multithreaded programming. This freedom comes at a cost, though: it
means that to write smoothly running software, you have to think asynchronously,
and not just for user input. Thinking this way can be difficult at first, especially if
you’re coming from a language where execution is normally synchronous.
JavaScript has had a mechanism for asynchronous execution from the earliest days of
the language. However, as the popularity of JavaScript has grown—and the sophisti‐
cation of the software being written for it—new constructs to manage asynchronous
programming have been added to the language. As a matter of fact, we can think of
JavaScript as having three distinct eras of asynchronous support: the callback era, the
promise era, and the generator era. If it were a simple matter of generators being bet‐
ter than everything that came before them, we would explain how generators work
199