Key Takeaways
Treat JavaScript as queued work, not as many threads taking turns
One stack runs at a time. In the book's model, JavaScript runs current code to completion before queued event handlers can execute. A timer does not interrupt a busy script. It makes a callback eligible to run after the delay, once the thread is free. That is why a loop lasting a second can postpone a callback scheduled for half a second, and why a zero-delay timer means later, not now.
Closures matter, too. In a loop using `var i`, three scheduled callbacks can all read the same variable after the loop has finished, producing three copies of the final value rather than three distinct values. The event queue avoids one class of shared-state race, but it does not make every asynchronous behavior predictable. Timers are imprecise, and long-running code still freezes the page.
What's useful here is the shift from imagining parallel execution to tracking when work becomes eligible and when it can actually run. That model makes delayed callbacks, UI freezes, and surprising output easier to reason about. It also resembles cooperative scheduling: each task must yield by returning before another queued task gets a turn. The limit matters, though. A single JavaScript thread does not prevent logical races, where outcomes depend on which response arrives first, nor does it make slow tasks harmless. The model clarifies scheduling, but it does not replace careful state design.
Make every callback consistently asynchronous, and stop polling for results
Fast paths can surprise. A function may call its callback immediately when it has a cached answer, but call it later when it must perform I/O. Code using that function now has two different timing behaviors. The book's example is a calculation requested from a worker: repeatedly scheduling a timer to check whether the result has appeared is async recursion, an inefficient form of polling that creates needless queued work.
Store listeners instead. If several callers request the same calculation before it finishes, keep their callbacks in a list for that calculation. When the worker returns, save the result and notify the waiting callers. For a cached result, arrange the callback to run after the function returns, or otherwise guarantee one consistent contract. A zero-delay timer can defer execution, but it is not a precise clock.
An asynchronous API has a temporal contract as well as a data contract. Keeping callback timing consistent prevents callers from needing to handle separate cases for cached and uncached results, a problem closely related to reentrancy in event-driven systems. Listener storage also expresses the actual dependency: these callers are waiting for one result, not repeatedly asking whether it has arrived. Polling can sometimes be necessary when an interface provides no notification mechanism, but it should be a deliberate workaround rather than the default design.
Handle async failures where callbacks arrive, not around the scheduling call
The surrounding catch is too early. A `try/catch` around `setTimeout` cannot catch an exception thrown inside its callback, because the callback runs later, after the original call stack has ended. The same principle applies to other asynchronous operations. In Node-style APIs, callbacks commonly receive an error as their first argument, giving the callback a chance to handle failure where the result arrives. Browser libraries may instead provide separate success and failure handlers.
Give errors an owner. The book recommends handling ordinary failures near their source: show an error, retry, or choose another appropriate response. Global handlers such as the browser's `window.onerror` or Node's uncaught-exception mechanisms are presented as debugging or last-resort tools, not routine recovery plans. Throwing inside an async callback usually sends the error to the environment's uncaught-error machinery.
This is a useful boundary rule: an error should be handled by code that still has enough context to make a meaningful decision. It parallels distributed systems, where a request can fail after the initiating function has returned, so failure must travel through an explicit channel. Treating errors as callback data makes that channel visible, though it also places responsibility on each caller to avoid silently ignoring failures. A global handler can record a failure, but recording is not the same as restoring a valid application state.
Use PubSub to fan out events, but check whether delivery is synchronous
One event, many listeners. PubSub, short for publish/subscribe, lets an object announce a named event while multiple independent handlers respond. Node's `EventEmitter`, Backbone's evented models, and jQuery's event system are examples in the book. A document editor, for instance, can react to a keystroke by updating the display, word count, undo history, and server sync without stuffing all those tasks into one oversized handler.
An event is not necessarily async. Triggering a jQuery event from application code runs its handlers immediately, in sequence. A handler that triggers the same event can create an infinite cycle. Backbone models publish changes when updated through their methods, and collections can relay those changes. Custom jQuery events can bubble through the DOM, so event propagation and application structure need deliberate boundaries.
PubSub reduces direct dependencies: the event producer need not know every listener or the order in which features were added. That resembles message-oriented architectures, where components coordinate through named signals rather than direct calls. The tradeoff is that the dependency graph becomes less visible. A change can trigger several listeners, possibly through bubbling or relaying, and synchronous handlers can still monopolize execution. Event naming, clear ownership, and cycle prevention are therefore not cosmetic details. They are what keep decoupling from turning into an invisible knot.
Give one-shot tasks Promises, and keep the power to settle them private
A Promise represents an outcome. The book defines a Promise as an object that holds callbacks for a one-time asynchronous task, such as an Ajax request, that can succeed or fail. In jQuery's terminology, `done` handles success, `fail` handles failure, and `always` handles either outcome. A pending Promise becomes resolved or rejected once, then does not change state. Some versions also provide progress notifications while work remains pending.
Separate control from observation. A jQuery `Deferred` is a Promise with methods such as `resolve` and `reject`, so its owner can settle it. Calling its `promise` method gives other parts of the program a read-only interface: they can attach handlers but cannot decide the task's outcome. That distinction supports encapsulation, whether the operation is an Ajax call, an animation, or a user choosing an option.
The distinction between a Deferred and its Promise is a small example of capability-based design: give each component only the authority it needs. The task owner can change state, while observers can react without interfering. This makes coordination safer and also clarifies responsibility when completion is delayed. The book discusses jQuery's particular vocabulary and API, so its details should not be mistaken for a universal Promise standard. The durable idea is the separation between controlling a task and observing its eventual result.
Compose Promise chains and joins instead of nesting dependent callbacks
Use a chain for dependency. In the book's jQuery API, `pipe` creates a new Promise based on a callback's result. If the callback starts another Promise-producing task, the new Promise follows that task. A sequence such as fetching data, posting it elsewhere, and then performing a final request can therefore be represented as a chain instead of callbacks buried inside callbacks. Failures can pass through the chain when no recovery handler changes the outcome.
Use a join for parallel work. `$.when` combines Promises, resolving when all supplied tasks succeed and rejecting if any fails. The example is starting a game only after both its server data has loaded and a tutorial video has ended. The book warns that unpacking all combined callback arguments can be awkward, so results can be collected on the individual Promises before the join.
These operations turn asynchronous tasks into a small algebra. A chain expresses dependency, while a join expresses a condition that several independent tasks must satisfy. That is more than syntactic cleanup: it makes the structure of a workflow inspectable. One important nuance is that a combined Promise reporting failure does not necessarily cancel the other work already underway. Composition organizes observation and result flow, but cancellation, cleanup, and retry policy still require explicit design. The book also stresses that Promise libraries can differ in behavior, so mixing their conventions carelessly undermines the clarity composition is meant to provide.
Choose series, parallel, or bounded queues by ordering and capacity
Choose the execution policy first. Async.js supplies collection operations and task runners for common patterns. Series methods run tasks one after another, preserving order and avoiding too many simultaneous I/O requests. Parallel methods start tasks together and collect results in the order of the task list, even if they finish in a different order. In the book's timer demonstration, three tasks taking about 100, 300, and 200 milliseconds take roughly 600 milliseconds in series and about 300 milliseconds in parallel.
Limit concurrency when needed. `async.queue` accepts tasks as they arrive and runs a worker up to a chosen concurrency limit. It is useful when there are many files or requests and unlimited parallel work could overwhelm a resource. Its completion callback signals that the queue has drained, but result ordering and collection are left to the application. The lighter Step library offers a more minimal alternative.
The important decision is not simply whether parallel work is faster. It is whether ordering, throughput, and resource limits fit the task. A bounded queue is an elementary form of backpressure: it prevents a producer from turning every available operation into simultaneous load. That idea appears throughout systems engineering, from database connection pools to network services. A queue can still conceal operational concerns, such as how failures affect remaining tasks or how results are indexed. Choosing the library method is only the first step; the application must define those policies too.
Send CPU-heavy work to isolated workers, and exchange messages deliberately
Keep expensive computation off the main thread. Browser Web Workers can run demanding work such as parsing code or decoding video without blocking the page's interaction. A worker cannot manipulate the DOM or inspect the main thread's objects. Instead, the two sides send messages, and objects are copied through serialization rather than shared directly. This preserves the book's event-based model while allowing work on another thread.
Use cores through separation. Node's `cluster` approach starts worker processes, commonly one per CPU core, with a master process coordinating them. Workers communicate by messages, not by freely sharing application state. The book advises keeping inter-worker communication limited and placing shared state in an external store when appropriate. Workers help when tasks can be divided into largely independent pieces; communication and data-copy costs make them a poor fit for every workload.
Message passing is a trade: isolation makes coordination easier to reason about, while communication adds cost and forces data boundaries into the open. This resembles actor-style systems, where independent units receive messages instead of mutating shared memory. It is especially attractive for computations that are expensive but can be separated cleanly. The qualification matters: moving work to another worker does not guarantee a faster application if serialization, coordination, or uneven task sizes dominate. The right question is whether the work can be partitioned with sufficiently little conversation.
Load scripts according to urgency, independence, and dependency order
Do not make every script a gate. A normal script can delay rendering while it downloads and runs. The book recommends keeping rendering-critical code early and moving less urgent scripts out of the critical path. In the browser context it describes, `defer` lets a script download while the document loads, then runs deferred scripts in order after the document is ready. `async` scripts run as soon as available, with no dependable order, so it suits independent widgets better than scripts with dependencies.
Choose a loader for complexity. Programmatic loading can fetch a script only when a feature or condition requires it. The book presents yepnope for lightweight conditional loading and Require.js for larger dependency graphs using Asynchronous Module Definition, or AMD. These are 2012-era tools and compatibility assumptions. Their enduring lesson is to make script priority and dependencies explicit rather than relying on accidental download timing.
Script loading is a scheduling problem at page scale: a fast page depends on which work blocks first use, not merely on how many files it contains. The distinction between ordered dependencies and independent work is the same one used in Promise composition and task queues. Dynamic loading can also reduce the work a user never needs, but it introduces failure modes, such as a feature being requested before its code is ready. The named browser APIs and libraries reflect the book's publication era. The prioritization principle remains useful even when the specific loading ecosystem changes.
Analysis
Burnham's strongest contribution is a practical taxonomy of asynchronous work. Events describe how something gets a turn to run. PubSub describes how one event reaches multiple listeners. Promises describe the eventual outcome of one task. Flow-control utilities describe how many tasks run, in what order, and with what concurrency. Workers move suitable work into isolated execution contexts, while script loaders decide which code should become available and when. These layers solve different problems, and much callback confusion comes from asking one layer to do another's job.
The book's narrative begins with the apparent curse of single-threaded JavaScript, then shows how that constraint can become a design advantage. Queued callbacks avoid interruption within a running handler, but the text also demonstrates where this comfort ends: callbacks may run synchronously on cached paths, events can form cycles, and results can arrive in unexpected orders. The deeper lesson is not that JavaScript eliminates concurrency hazards. It is that it makes many scheduling and state boundaries explicit, provided APIs maintain consistent timing and clear error contracts.
The most enduring advice is therefore architectural rather than library-specific: avoid polling, prevent callback nesting from carrying the whole workflow, separate event publishers from subscribers, and select a control-flow pattern that matches the task. A Promise chain is not a queue with capacity limits; PubSub is not inherently asynchronous; a worker is not shared-memory parallelism. Keeping these distinctions intact makes asynchronous systems easier to inspect.
The book is explicitly a 2012 guide. Its examples rely on then-current jQuery Promise behavior, Node conventions, browser support estimates, and script-loading libraries. Those details should be treated as a historical snapshot, not a present-day API reference. Yet the abstractions survive changes in syntax and tools because they address recurring questions: who owns a result, who handles failure, what must happen first, and how much simultaneous work is safe. That is why the book remains valuable as a way to think, even where its named tools have aged.
Review Summary
Async JavaScript receives mostly positive reviews, with readers praising its focused approach to asynchronous programming. Many find it informative and enlightening, highlighting its coverage of event queuing, promises, and web workers. Readers appreciate the book's concise nature and its ability to improve understanding of JavaScript's single-threaded model. Some criticize it for being outdated or lacking in-depth examples, but overall, it's recommended for those looking to enhance their JavaScript skills, especially in handling asynchronous operations and creating more responsive applications.
People Also Read
Glossary
event loop
runs queued callbacksThe mechanism described in the book in which JavaScript finishes its current execution before handling eligible queued events. Timers, user input, and other event sources can make callbacks ready, but those callbacks do not interrupt code already running. Long-running synchronous work therefore delays event handling and can make an application unresponsive.
PubSub
distributes named eventsShort for publish/subscribe, PubSub is a pattern in which an object announces a named event and any number of registered handlers can respond. Examples in the book include Node's EventEmitter, Backbone evented models, and jQuery events. PubSub reduces direct connections between components, but it does not guarantee asynchronous delivery.
Promise
represents a task outcomeA Promise is an object representing an asynchronous task and carrying callbacks for its eventual outcome. In the jQuery API discussed in the book, handlers can be attached for success, failure, or both. A Promise also supports composition, allowing code to represent dependent tasks or wait for several operations together.
Deferred
controls a Promise's outcomeIn jQuery's terminology in the book, a Deferred is a Promise with additional methods that let its creator resolve or reject it, and sometimes send progress notifications. Its promise method exposes an observation-only interface. Keeping the Deferred private allows other parts of an application to attach handlers without controlling when the task completes.
Pyramid of Doom
deeply nested callbacksThe book's name for async code that nests each new callback inside the preceding callback. As sequential steps accumulate, indentation and control flow become difficult to follow and extend. The book recommends named callbacks, event distribution, Promises, and flow-control utilities as ways to make the sequence more manageable.
async.queue
limits concurrent tasksAn Async.js utility that accepts tasks dynamically and runs a worker function on them up to a specified concurrency limit. Tasks wait until a worker slot is available. The queue can signal when it becomes empty or drains, but the application must manage result collection and ordering when those matter.
Web Workers
run isolated browser tasksBrowser workers execute JavaScript outside the page's main thread, making them useful for demanding computations that would otherwise delay interaction. They cannot directly manipulate the DOM or access the main thread's objects. Communication happens through messages, with data copied rather than freely shared.
Asynchronous Module Definition (AMD)
declares script dependenciesAMD is a module format described in the book for browser applications. A module declares its dependencies and provides a callback that receives them once they are loaded. A loader such as Require.js can use those declarations to fetch scripts in parallel while executing them in dependency order.
FAQ
What's "Async JavaScript" by Trevor Burnham about?
- Focus on Asynchronous JavaScript: The book is dedicated to understanding and mastering asynchronous JavaScript, which is crucial for building responsive web applications.
- Concurrency and Event Handling: It explores how to handle concurrency and asynchronous tasks effectively without getting overwhelmed by complexity.
- Practical Examples: The book provides practical examples and code snippets to illustrate how to implement asynchronous patterns in both client-side and server-side JavaScript.
- Comprehensive Guide: It serves as a comprehensive guide for intermediate JavaScript developers looking to deepen their understanding of asynchronous programming.
Why should I read "Async JavaScript" by Trevor Burnham?
- Improve Responsiveness: Learn how to build more responsive applications by effectively managing asynchronous operations.
- Avoid Common Pitfalls: The book helps you avoid common pitfalls associated with asynchronous JavaScript, such as callback hell and race conditions.
- Enhance JavaScript Skills: It is an excellent resource for intermediate developers to enhance their JavaScript skills, particularly in handling asynchronous tasks.
- Practical Insights: Gain practical insights and techniques that can be directly applied to real-world projects, improving both code quality and performance.
What are the key takeaways of "Async JavaScript" by Trevor Burnham?
- Understanding Events: A deep dive into JavaScript's event model and how asynchronous events are scheduled and handled.
- Promises and Deferreds: Learn about Promises and Deferreds, which are essential for managing asynchronous operations in a more structured way.
- Flow Control Libraries: Introduction to libraries like Async.js and Step, which help manage complex asynchronous flows.
- Multithreading with Workers: Explore how to use web workers and Node.js workers to leverage multithreading in JavaScript applications.
How does "Async JavaScript" explain JavaScript events?
- Conceptual Elegance: The book explains that JavaScript events are conceptually elegant and practical, allowing for uninterruptible code execution.
- Event Scheduling: It covers how events are scheduled and executed in JavaScript, emphasizing the single-threaded nature of the language.
- Event Queue: The book describes the event queue mechanism, where events are queued and executed sequentially once the current execution stack is clear.
- Practical Examples: Provides practical examples to illustrate how to handle events and avoid common issues like the "Pyramid of Doom."
What are Promises and Deferreds in "Async JavaScript"?
- Promises Defined: Promises are objects representing a task with two possible outcomes: success or failure, allowing for structured handling of asynchronous operations.
- Deferreds as Supersets: A Deferred is a superset of a Promise, providing additional methods to trigger the Promise's state changes.
- Encapsulation Benefits: Promises allow for better encapsulation of asynchronous tasks, making it easier to manage multiple callbacks and reduce code duplication.
- Combining Promises: The book explains how to combine Promises to manage complex asynchronous flows, such as waiting for multiple tasks to complete.
How does "Async JavaScript" address flow control with Async.js?
- Async.js Overview: Async.js is introduced as a powerful library for managing asynchronous flows, particularly in Node.js environments.
- Collection Methods: The book covers Async.js's collection methods like
forEach,map, andfilter, which simplify handling arrays of asynchronous tasks. - Task Organization: It explains how to organize tasks using methods like
series,parallel, andqueueto control the execution order and concurrency. - Error Handling: Async.js's approach to error handling is discussed, showing how errors are propagated through callbacks to a final handler.
What is the role of web workers in "Async JavaScript"?
- Multithreading Solution: Web workers are presented as a solution for leveraging multithreading in JavaScript without sharing state between threads.
- Separate Execution: Workers run code in separate threads, allowing for complex computations without blocking the main thread.
- Message Passing: The book explains how to communicate with workers using message passing, maintaining the event-driven nature of JavaScript.
- Practical Applications: Examples of practical applications for web workers, such as video decoding and data parsing, are provided.
How does "Async JavaScript" suggest handling async script loading?
- Script Loading Challenges: The book addresses the challenges of script loading, such as blocking and nonblocking scripts, and their impact on page performance.
- HTML5 Attributes: It introduces HTML5 attributes like
asyncanddeferto optimize script loading and execution order. - Script Loading Libraries: Libraries like yepnope and Require.js are discussed for more advanced script loading scenarios, including conditional and modular loading.
- Performance Optimization: Emphasizes the importance of optimizing script loading to improve page load times and user experience.
What are the best quotes from "Async JavaScript" and what do they mean?
- "JavaScript now works." This quote highlights the evolution of JavaScript from a language often criticized for its limitations to a powerful tool for web development.
- "Any application that can be written in JavaScript will eventually be written in JavaScript." Known as Atwood's Law, this quote underscores JavaScript's ubiquity and versatility across different platforms and applications.
- "I love async, but I can’t code like this." This quote reflects the common frustration with callback hell and the need for better async management techniques.
- "Let’s prove to the world that even the most complex problems can be tackled with clean, maintainable JavaScript code." This quote encapsulates the book's mission to empower developers to write efficient and maintainable asynchronous JavaScript.
How does "Async JavaScript" explain the use of PubSub?
- PubSub Pattern: The book introduces the publish/subscribe pattern (PubSub) as a way to distribute events across an application.
- EventEmitter in Node.js: It explains how Node.js's EventEmitter provides a built-in PubSub mechanism for handling events.
- Evented Models: Discusses the use of evented models in frameworks like Backbone.js to manage application state changes and trigger events.
- Custom jQuery Events: The book also covers how to use custom jQuery events for distributing DOM-related events efficiently.
What are the practical applications of "Async JavaScript" concepts?
- Responsive Web Apps: The concepts help in building more responsive web applications by efficiently managing asynchronous tasks.
- Server-Side JavaScript: Techniques like Promises and Async.js are applicable in server-side JavaScript environments, such as Node.js, for handling I/O operations.
- Complex Event Handling: The book provides strategies for handling complex event-driven architectures, making it easier to manage large-scale applications.
- Performance Optimization: By understanding and applying async patterns, developers can optimize performance and improve user experience in web applications.
What resources does "Async JavaScript" recommend for further learning?
- JavaScript Weekly: The book recommends JavaScript Weekly for staying updated with the latest JavaScript news and trends.
- Codecademy and CodeSchool: These platforms are suggested for interactive tutorials and courses to learn JavaScript and related technologies.
- Eloquent JavaScript: A formal introduction to JavaScript is recommended through the book "Eloquent JavaScript" by Marijn Haverbeke.
- Mozilla Developer Network: For reliable JavaScript documentation and resources, the book advises using the Mozilla Developer Network (MDN).
Download PDF
Download EPUB
.epub digital book format is ideal for reading ebooks on phones, tablets, and e-readers.