Chapter 4. Generators
In Chapter 2, we identified two key drawbacks to expressing async flow control with callbacks:
-
Callback-based async doesn’t fit how our brain plans out steps of a task.
-
Callbacks aren’t trustable or composable because of inversion of control.
In Chapter 3, we detailed how Promises uninvert the inversion of control of callbacks, restoring trustability/composability.
Now we turn our attention to expressing async flow control in a sequential, synchronous-looking fashion. The “magic” that makes it possible is ES6 generators.
Breaking Run-to-Completion
In Chapter 1, we explained an expectation that JS developers almost universally rely on in their code: once a function starts executing, it runs until it completes, and no other code can interrupt and run in between.
As bizarre as it may seem, ES6 introduces a new type of function that does not behave with the run-to-completion behavior. This new type of function is called a generator.
To understand the implications, let’s consider this example:
varx=1;functionfoo(){x++;bar();// <-- what about this line?console.log("x:",x);}functionbar(){x++;}foo();// x: 3
In this example, we know for sure that bar() runs in between x++ and
console.log(x). But what if bar() wasn’t there? Obviously the result
would be 2 instead of 3.
Now let’s twist your brain. What if bar() wasn’t present, but it could
still somehow run between the x++ and console.log(x) statements? How
would that be possible?
In preemptive ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access