Chapter 8: Functions for the future: promises and generators
The chapter introduces promises as a modern alternative to callbacks for dealing with future events and previews async/await and generators.
After this chapter you will be able to
- Promises and future events. Explain that callbacks can run when a future event occurs, but promises offer another way to deal with such events by representing an event as an object.
- Promise outcomes and callbacks. Explain that a promise represents an operation’s outcome and, in the timer example, separates the event result from a callback passed directly to setTimeout.
- Shareable promises and multiple handlers. Describe how passing a promise to other code lets that code attach handlers, how then can be called repeatedly on the same promise, and how these properties support higher-level operations involving multiple promises.
- Promise states and settlement. Describe the three promise states and explain what becomes fixed when a promise settles.
- Promise constructor and rejection. Explain what the promise constructor's executor does and how rejection can occur.
- Thenable resolution versus settlement. Distinguish resolving with a normal value from resolving with a thenable, and explain why resolved does not necessarily mean settled.
- New promises from handlers. Explain that then returns a new pending promise whose outcome depends on its callback: a returned value resolves it, a thrown reason rejects it, and a returned promise determines its eventual outcome. State that handlers do not change the promise they are attached to.
- Errors across a chain. Explain why a single catch handler can receive errors from different operations in a promise chain, including fetch(), a thrown error for an unsuccessful response, and response.json().
- All or nothing outcomes. Explain when to use Promise.all and what its returned promise does when every input fulfills or any input rejects.
- First successful promise outcome. Explain how Promise.any chooses an outcome and why it fits alternative ways to complete one task.
- First settlement and timeout cleanup. Describe how Promise.race can impose a time limit and why an AbortController is also used for the fetch.
- Asynchronous then callback timing. Explain why a then callback runs after the code following a then call, even when the promise is already settled.
- Microtask and macrotask priority. Trace how the event loop orders synchronous code, promise callbacks, and timeout callbacks. Distinguish the microtask queue from the macrotask queue.
- Await and promise syntax. Explain that await is commonly used in place of .then() chains because it retains the power of promises while making code resemble synchronous code.
- Nested callback state tradeoff. Explain why a series of asynchronous callbacks can become hard to read and why moving callbacks into separate named functions does not fully solve the problem.
- Readable asynchronous calls with await. Describe what await changes about the way a series of promise-based asynchronous calls can be written, without claiming that the calls become synchronous.
- Await and promise settlement. Trace what happens when JavaScript evaluates await value, including how execution resumes after fulfillment or rejection.
- Permitted await locations. State where await is allowed and why the section restricts its use.
- Async function promise outcomes. Explain how declaring a function async changes its returned and thrown values: a returned value becomes a fulfilled promise, while a thrown value becomes a rejected promise.
- Await and caller execution. Explain why await can be used inside an async function without interrupting the caller’s flow of execution.
- Generator functions and iterables. Explain that generators provide a convenient syntax for defining a function that returns an iterable, much as async provides a convenient syntax for defining a function that returns a promise.
- Iterable and iterator protocol. Explain what makes an object iterable and distinguish it from the iterator it returns. Describe the required Symbol.iterator function and the shape of each next() result.
- Iterable consumption syntax. Explain how for…of and destructuring use iterators, including why destructuring is not limited to arrays.
- Generator function and object. Distinguish a generator function from the generator object it returns, and describe how each is defined or used.
- Yield and next progression. Trace what happens when next() advances a generator to a yield, a return, or an error.
- Yield delegation and recursion. Describe how yield* delegates to another generator and why recursive delegation can help traverse a tree.
- Yield versus asynchronous waiting. Distinguish what yield does from what await does, and explain why combining yield with async and await is useful in a generator.
- Async iterable protocol. Describe how an async iterable supplies an async iterator and how its next() result differs from a synchronous iterator’s.
- Async generator consumption. Describe how to define an async generator and how for await…of consumes an async iterator, including the stated limits on other iteration syntax.
What it builds on
- Callback functions (chapter 5) · Introduces callback functions.
- Event-handling overview (chapter 4) · The earlier event-handling overview.
- Defining return types in TypeScript (chapter 5) · Reading function return types in TypeScript
Section by section
Introduction
The chapter introduces promises as a modern alternative to callbacks for dealing with future events and previews async/await and generators.
- Promises and future events: Explain that callbacks can run when a future event occurs, but promises offer another way to deal with such events by representing an event as an object.
Why it matters: This distinction sets up why the chapter turns from callbacks to promises.
Key terms: callback, promise, event
8.1 The power of promises
This section introduces promises as objects that represent operation outcomes and explains why separating an outcome from its callback is useful.
- Promise outcomes and callbacks: Explain that a promise represents an operation’s outcome and, in the timer example, separates the event result from a callback passed directly to setTimeout.
Why it matters: This distinction explains why using a promise can offer more flexibility than passing a callback directly. - Shareable promises and multiple handlers: Describe how passing a promise to other code lets that code attach handlers, how then can be called repeatedly on the same promise, and how these properties support higher-level operations involving multiple promises.
Why it matters: Sharing one promise among handlers is part of what makes promises useful for coordinating operations.
Key terms: promise, callback, outcome of an operation, handler, then, resolved
8.1.1 Resolving and settling promises
This section explains promise states, how promises are resolved or rejected, and why resolving a promise does not always settle it.
- Promise states and settlement: Describe the three promise states and explain what becomes fixed when a promise settles.
Why it matters: These states provide the vocabulary for describing what happens to a promise. - Promise constructor and rejection: Explain what the promise constructor's executor does and how rejection can occur.
Why it matters: It clarifies where a newly created promise gets its outcome. - Thenable resolution versus settlement: Distinguish resolving with a normal value from resolving with a thenable, and explain why resolved does not necessarily mean settled.
Why it matters: This distinction prevents treating every call to resolve as immediate fulfillment. - External resolvers and callbacks: Describe what Promise.withResolvers() returns and how its resolve function can bridge a callback-based API to a promise.
Why it matters: It gives a direct way to represent the result of a callback-based operation as a promise.
Key terms: pending, fulfilled, rejected, settled, executor, resolve, reject, reason, thenable, resolved
8.1.2 Chaining promises with then()
Explains how promise handlers create chains, how errors flow to catch, and how finally runs after settlement.
- New promises from handlers: Explain that then returns a new pending promise whose outcome depends on its callback: a returned value resolves it, a thrown reason rejects it, and a returned promise determines its eventual outcome. State that handlers do not change the promise they are attached to.
Why it matters: This is what makes a sequence of promise operations possible. - Errors across a chain: Explain why a single catch handler can receive errors from different operations in a promise chain, including fetch(), a thrown error for an unsuccessful response, and response.json().
Why it matters: One rejection handler can cover failures at several steps without separate error-handling callbacks for each step. - Finally after promise settlement: Describe when a finally handler runs and distinguish it from a handler that runs only for fulfillment or rejection.
Why it matters: It provides a place for a handler that should run regardless of how the promise settles.
Key terms: then, onFulfilled, onRejected, pending, resolve, reject, catch, promise chain, fetch(), response.ok
8.1.3 Dealing with multiple promises
This section explains how to combine concurrent promises, choose among their outcomes, handle timeouts, and recognize when a concurrency-limiting utility is needed.
- All or nothing outcomes: Explain when to use Promise.all and what its returned promise does when every input fulfills or any input rejects.
Why it matters: It lets you wait for concurrent work when every result is needed. - Settled outcomes for every promise: Distinguish Promise.allSettled from Promise.all when the outcome of every operation matters despite failures.
Why it matters: It preserves information about every operation when a single failure should not end the report. - First successful promise outcome: Explain how Promise.any chooses an outcome and why it fits alternative ways to complete one task.
Why it matters: It suits tasks with several possible sources where any successful answer will do. - First settlement and timeout cleanup: Describe how Promise.race can impose a time limit and why an AbortController is also used for the fetch.
Why it matters: Winning the race does not itself stop the losing network request. - Limits of promise combinators: Explain why the built-in multi-promise methods do not manage resource-constrained concurrency and identify the utility offered for that job.
Why it matters: Starting every task at once can exhaust resources, such as memory for Web Workers.
Key terms: Promise.all, fulfilled values, rejection reason, Promise.allSettled, settled states, Promise.any, first promise to be fulfilled, Promise.race, AbortController, signal
8.1.4 Promise timing: Of microtasks and macrotasks
Explains why promise callbacks run after synchronous code but before timeout callbacks, using the event loop’s microtask and macrotask queues.
- Asynchronous then callback timing: Explain why a then callback runs after the code following a then call, even when the promise is already settled.
Why it matters: This lets you predict what runs immediately after attaching a promise callback. - Microtask and macrotask priority: Trace how the event loop orders synchronous code, promise callbacks, and timeout callbacks. Distinguish the microtask queue from the macrotask queue.
Why it matters: Queue priority explains why a promise callback can run before a timeout even when both are waiting. - Direct microtask scheduling: Describe why developers have used promise callbacks to schedule asynchronous work ahead of timeouts, and name the more direct API the section gives for that purpose.
Why it matters: It connects the queue ordering to a practical choice for scheduling asynchronous work.
Key terms: settled promise, then callback, event loop, microtask queue, job queue, macrotask queue, task queue, microtasks, queueMicrotask, setTimeout
8.2 Flattening promise callbacks with await
Introduces await as a simpler-looking way to work with promises than the .then() chains common in earlier JavaScript code.
- Await and promise syntax: Explain that await is commonly used in place of .then() chains because it retains the power of promises while making code resemble synchronous code.
Why it matters: This distinction explains why await is a staple of modern JavaScript code.
Key terms: promises, .then(), await
8.2.1 The problem with nested callbacks
This section explains why nested callbacks make sequences of asynchronous operations hard to read and introduces await as a more readable way to express them.
- Nested callback state tradeoff: Explain why a series of asynchronous callbacks can become hard to read and why moving callbacks into separate named functions does not fully solve the problem.
Why it matters: This tradeoff explains why simply rearranging callbacks does not make a sequence of async operations easy to follow. - Readable asynchronous calls with await: Describe what await changes about the way a series of promise-based asynchronous calls can be written, without claiming that the calls become synchronous.
Why it matters: It identifies the improvement await offers while keeping the underlying asynchronous model distinct from the code’s appearance.
Key terms: callbacks, callback hell, state, promises, await, promise-based APIs, event-driven single-threaded model
8.2.2 How await works
Explains how await pauses the current code without blocking other events, how it resumes or throws, and where JavaScript permits its use.
- Await and promise settlement: Trace what happens when JavaScript evaluates await value, including how execution resumes after fulfillment or rejection.
Why it matters: This explains why awaiting a result does not stop other events from running. - Await syntax and errors: Explain the practical advantages described here of using await instead of then callbacks.
Why it matters: These features help make asynchronous code easier to express and errors easier to trace. - Permitted await locations: State where await is allowed and why the section restricts its use.
Why it matters: The restriction makes it possible to recognize where code may pause without assuming every function call can interrupt its caller.
Key terms: await, Promise.resolve(value), settled, microtask, fulfilled, rejected, then, stack trace, ECMAScript module (ESM), top level
8.2.3 Automating promise creation with async
This section explains how async functions automatically return promises, turn thrown errors into rejections, and make await safe to use without interrupting the caller.
- Async function promise outcomes: Explain how declaring a function async changes its returned and thrown values: a returned value becomes a fulfilled promise, while a thrown value becomes a rejected promise.
Why it matters: You can use ordinary return and throw statements while giving callers a consistent promise-based result. - Await and caller execution: Explain why await can be used inside an async function without interrupting the caller’s flow of execution.
Why it matters: This distinguishes a pause inside an async function from a pause in the code that called it. - Async return types in TypeScript: Describe what a TypeScript async function’s return type shows and how its rejection reason is typed.
Why it matters: The type makes the promise return visible without implying that TypeScript fixes the type of a rejection.
Key terms: async function, promise resolution algorithm, rejected promises, await, promise, Promise<string>, fulfilled value, rejection reason, unknown
8.3 Making interruptible loops with generators
Introduces generators as a way to define functions that return iterables and explains why their anticipated role in asynchronous code diminished.
- Generator functions and iterables: Explain that generators provide a convenient syntax for defining a function that returns an iterable, much as async provides a convenient syntax for defining a function that returns a promise.
Why it matters: This connection gives you a starting point for the upcoming discussion of iterables and generators. - Generators in asynchronous JavaScript: Describe how generators and promises were expected to help replace nested callbacks, but async and await later displaced one of generators’ major uses.
Why it matters: This explains why generators are worth recognizing without treating them as the standard solution to nested callbacks.
Key terms: generators, iterable, async, promise, promises, nested callbacks, async and await
8.3.1 Iterables and iterators
This section explains the iterator protocol that lets JavaScript consume sequential values from arrays, other collections, and custom iterables.
- Iterable and iterator protocol: Explain what makes an object iterable and distinguish it from the iterator it returns. Describe the required Symbol.iterator function and the shape of each next() result.
Why it matters: This protocol explains how JavaScript can iterate over objects beyond arrays. - Iterable consumption syntax: Explain how for…of and destructuring use iterators, including why destructuring is not limited to arrays.
Why it matters: It connects familiar array syntax to the more general iterable protocol. - Lazy and unbounded iterables: Describe how an iterable can produce values on demand rather than hold a fixed collection, and explain the caution about spreading all its values.
Why it matters: An iterable may generate values indefinitely, making attempts to collect every value unsafe.
Key terms: Symbol.iterator, iterable, iterator, next(), iterator result, value, for…of, destructuring, spread, rest
8.3.2 Iterating within a function with generators
This section explains how generator functions produce iterable generator objects that pause and resume at yields, accept values through next(), and delegate iteration with yield*.
- Generator function and object: Distinguish a generator function from the generator object it returns, and describe how each is defined or used.
Why it matters: This distinction makes it clear which thing you declare and which thing you iterate. - Yield and next progression: Trace what happens when next() advances a generator to a yield, a return, or an error.
Why it matters: The pause-and-resume behavior explains how a function can supply successive values without losing its place. - Values passed through next: Explain how a value passed to next() enters a resumed generator function.
Why it matters: A generator can receive information as well as yield it. - Yield delegation and recursion: Describe how yield* delegates to another generator and why recursive delegation can help traverse a tree.
Why it matters: Delegation lets one generator expose values from another, including during recursive traversal.
Key terms: generator function, generator object, function*, iterable, iterator, Symbol.iterator, next(), yield, value, done
8.3.3 Async iterables and async generators
This section explains how async generators combine iteration with asynchronous waiting, how their results are consumed, and when wrapping work in an iterable is useful.
- Yield versus asynchronous waiting: Distinguish what yield does from what await does, and explain why combining yield with async and await is useful in a generator.
Why it matters: It explains what async generators add to ordinary generators. - Async iterable protocol: Describe how an async iterable supplies an async iterator and how its next() result differs from a synchronous iterator’s.
Why it matters: The promise-returning next() result is the basis for asynchronous iteration. - Async generator consumption: Describe how to define an async generator and how for await…of consumes an async iterator, including the stated limits on other iteration syntax.
Why it matters: It connects the async generator definition to the syntax used to consume its results. - Generators as iterable wrappers: Explain the practical reason the section gives for using generators, with an example of a loop they can make easier to consume.
Why it matters: It gives a practical reason to consider a generator when a loop becomes complex.
Key terms: yield, await, async generators, Symbol.asyncIterator, async iterable, async iterator, next(), promise, async, function*
8.4 Summary
Where this is used later
- Defining and redefining object properties (chapter 9) · The earlier introduction to symbols as object keys.
- Common operations on arrays (chapter 10) · The idea of iterating over values with for…of.
- Using buffers to receive data (chapter 11) · Introduces async iteration used by the example’s async for…of loop.
- Reading and writing streams (chapter 11) · Async iteration with for await…of
Concepts explained in this chapter
- promiseThe ECMAScript constructor and associated object abstraction for representing the eventual completion or failure of an asynchronous operation.
- async/awaitJavaScript syntax for expressing asynchronous control flow using async functions and await expressions.
- iteration resultAn object with value and done properties describing the outcome of an iterator step.
- iterableAn iterable is an object that exposes an iteration protocol allowing its values to be traversed sequentially.
- async functionThe async keyword marks a function whose return value is wrapped in a promise and whose thrown errors reject that promise.
- then methodA then method accepts fulfillment and rejection callbacks, allowing an object to participate in promise-like resolution.
- iteratorAn iterator is an object that advances through a sequence and reports each successive iteration result.
- nextAn iterator method that advances iteration and returns an iterator result.
- fulfilled stateThe fulfilled state is a promise state indicating that the asynchronous operation completed successfully with a value.
- pending stateA pending state is the promise state in which the asynchronous operation has not yet fulfilled or rejected.
- rejected stateThe rejected state is a promise state indicating that the asynchronous operation failed with a rejection reason.
- generatorA generator is a JavaScript function whose execution can suspend and resume while producing a sequence of values through an iterator.
- concurrencyConcurrency is the overlapping progress of multiple operations during the same period of execution.
- Promise.allA static Promise method that fulfills with an ordered array of results when all inputs fulfill and rejects if any input rejects.
- Promise.racePromise.race is a static Promise method that creates a promise settled according to the first supplied promise to settle.
- yieldA yield expression is an expression inside a generator function that suspends execution and evaluates to a value supplied when the generator resumes.
- Promise.withResolversPromise.withResolvers is a static JavaScript method that returns a new promise together with its resolve and reject functions.
- executorAn executor is the callback passed to a promise constructor that runs immediately and receives functions for resolving or rejecting the promise.
- resolveA resolve function is the function associated with a promise that resolves it with a value or causes it to adopt a thenable's outcome.
- resolved promiseA resolved promise is a promise whose resolve or reject function has been called, including one that adopts the state of another promise or thenable.
- resolved stateA settled promise is a promise in either the fulfilled or rejected state whose state and associated value cannot change.
- thenableA thenable is an object with a then method whose behavior can be adopted by a promise.
- event loopAn event loop is a mechanism that repeatedly processes queued tasks and callbacks to support asynchronous, event-driven execution.
- destructuring assignmentDestructuring syntax assigns values extracted from an iterable or other structured value to program bindings.
- for...ofJavaScript loop syntax that retrieves successive values from an iterable.
- callbackA function supplied to another computation to be invoked when a specified event occurs or operation completes.
These guides are generated from the text of Manning books by Manning's knowledge graph and link to the sections they draw on. The full books are available on liveBook and at manning.com.
