Chapter 4. Async Flow Control
It’s no secret if you’ve written any significant amount of JavaScript that asynchronous programming is a required skill. The primary mechanism for managing asynchrony has been the function callback.
However, ES6 adds a new feature that helps address significant shortcomings in the callbacks-only approach to async: Promises. In addition, we can revisit generators (from the previous chapter) and see a pattern for combining the two that’s a major step forward in async flow control programming in JavaScript.
Promises
Let’s clear up some misconceptions: Promises are not about replacing callbacks. Promises provide a trustable intermediary—that is, between your calling code and the async code that will perform the task—to manage callbacks.
Another way of thinking about a Promise is as an event listener, upon which you can register to listen for an event that lets you know when a task has completed. It’s an event that will only ever fire once, but it can be thought of as an event nonetheless.
Promises can be chained together, which can sequence a series of
asychronously completing steps. Together with higher-level abstractions
like the all(..) method (in classic terms, a “gate”) and the
race(..) method (in classic terms, a “latch”), promise chains provide
an approximation of async flow control.
Yet another way of conceptualizing a Promise is that it’s a future value, a time-independent container wrapped around a value. This container can be reasoned about ...
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