Async JavaScript Pitfalls
Async and Streaming JavaScript: Comprehensive Study Notes
Async Programming Challenges
Asynchronous programming is inherently difficult, leading to concurrency bugs and complex code.
Common patterns like callbacks and events often create more problems than they solve, especially when combining multiple async sources.
Callback hell (deeply nested functions) obscures program logic and makes error handling and maintenance extremely difficult.
Event-based programming requires manual state management (e.g., tracking mouse down/up status) and careful addition/removal of event listeners, leading to brittle code.
"I thought I had a problem: I'll solve it with callbacks and events. Now I have two problems."
The Asynchronous Programming Landscape
A useful mental model places async patterns into four quadrants based on two axes:
Sync vs. Async (how values are delivered)
Single value vs. Multiple values (count of values produced)
Synchronous Single Value
Plain function call / variable assignment
let x = 5;— immediate, single value.Direct and straightforward.
Synchronous Multiple Values (Iterables)
Arrays, Maps, Sets,
arguments, etc.Can be processed with higher-order operations like
map,filter,forEach.Already familiar to JavaScript developers.
Asynchronous Single Value
Callbacks — a function passed to handle a future value.
Promises — a first-class object representing a single future value.
Unlike callbacks, promises can be passed around, returned from functions, and combined.
Example:
fetch(url).then(data => ...).
Asynchronous Multiple Values
Observables — first-class objects representing asynchronous streams of values.
Can use the same operations as iterables (
map,filter,reduce,forEach) without changing client code.This design is intentional: if you know how to program against collections, you know how to program against observables.
"Your mouse is also a database — a database of coordinates you'll get eventually when the mouse moves."
Key insight: All four quadrants are unified by treating async streams as first-class citizens that can be passed, returned, and composed like any other value.
Promises: Pros and Cons
What Promises Solve
Eliminate callback hell through chaining:
.then()/.catch().Composability: combine multiple async operations (e.g.,
Promise.all).Single value guarantees: once resolved, everyone gets the same answer.
Error propagation via
.catch().
Promise Limitations (within ES6 spec)
No built-in cancellation — once started, a promise cannot be aborted.
Useful for auto-complete: you may not care about an old request when the user types a new letter.
Workarounds: cancellation tokens, third-party libraries (e.g., Bluebird), sub-classing
Promise.
Only models single values — not suitable for streams or events.
No backpressure — a promise eagerly executes, which can overload servers or clients.
Reactive Programming & Observables
What Is Reactive Programming?
Reactive programming means responding to stimuli — not just events, but also load, failure, and user interaction.
React to events: handle clicks, key presses, mouse movements.
React to load: scale instances, drop data to maintain performance.
React to failure: retry, fallback to cache, degrade gracefully.
React to users: keep UI responsive at all times.
The Observable Pattern
An Observable is a push-based collection that emits values over time. It brings the power of array methods (map, filter, reduce) to async streams.
Mouse Drag Example — Observable Version
Instead of managing mousedown/mousemove/mouseup state manually, express the drag as a pipeline:
const mouseDowns = fromEvent(element, 'mousedown');
const mouseMoves = fromEvent(document, 'mousemove');
const mouseUps = fromEvent(document, 'mouseup');
const drags = mouseDowns.flatMap(md => {
const start = { x: md.clientX, y: md.clientY };
return mouseMoves
.takeUntil(mouseUps) // stop on mouse up
.map(mm => ({
left: mm.clientX - start.x,
top: mm.clientY - start.y
}));
});flatMapflattens the stream of mouse move streams into a single stream of offsets.takeUntilterminates the inner stream whenmouseUpfires.Result: a clean, declarative, composable description.
Auto-Complete Example with Throttle
const searchInput = document.getElementById('search');
const keyups = fromEvent(searchInput, 'keyup');
keyups
.map(e => e.target.value)
.filter(text => text.length >= 2)
.throttle(500) // wait 500ms of inactivity
.flatMapLatest(query => fetch(`/search?q=${query}`)) // take only latest
.subscribe(displayResults);throttle(debounce) prevents overloading the server.flatMapLatestensures only the last request's response is used, automatically discarding out-of-order replies.
Observables vs. FRP (Functional Reactive Programming)
Observables (as in RxJS) are discrete — they emit values only when events fire.
FRP (true meaning) deals with continuous time — behaviors that have a value at every instant (e.g., mouse position as a function of time).
Most libraries that call themselves FRP are actually observable libraries (map/filter/reduce on streams). Real FRP is a different concept.
Generators & Async/Await
Generators (function* / yield)
Suspend execution at
yieldand resume when the generator is advanced.Can be used to write async code with an imperative, linear style.
Example:
coorRxJSlibraries allowyieldon promises/observables.Drawback: syntax (
*,yield) can be confusing; error/resource management is manual.
Async/Await (ES7 stage 1 approved)
async function+awaitmakes asynchronous code look synchronous.No
function*oryield— justawaita promise.Example:
async function animate() { await delay(1000); await otherAsyncTask(); }Clear and explicit —
awaitmarks asynchronous points.Works naturally with observables via helper libraries (e.g.,
await lastValueFrom(observable)).
CSP (Communicating Sequential Processes)
Alternative model (e.g.,
js-csp).Requires manual error handling and resource management, which can be cumbersome.
Stream Processing
Node.js Streams Evolution
Streams1 (old): flawed —
pausedidn't work, data was pushed, no object mode.Streams2 (0.9/0.10): introduced
Readable,Writable,Duplex,Transform; object mode; explicitpause/resume.Streams3 (development): further refinements like
cork/uncorkfor bulk writes.Critique: still too imperative — requires manual management of pipe, drain, end events.
whatWG Streams (Browser Standardization)
Aim to standardize low-level I/O in browsers.
Concepts: ReadableStream, WritableStream, TransformStream.
Single reader / single writer to avoid complexity.
Still focused on low-level control rather than composable streams.
Dart's Approach
Dart unifies futures (single async values) and streams (multiple async values) into one consistent API.
I/O operations (files, sockets) use the same API as UI events.
This unification is a model for what JavaScript could become.
Reactive Streams (Backpressure)
A common criticism: "Observables don't support backpressure."
Solution: Observables can implement backpressure through:
Lossy: sampling, throttling (drop values).
Lossless: pauseable buffer (collect during pause, resume later).
Controlled: each subscription requests
Nitems explicitly.
Example of pauseable buffer:
const buffered = chattyObservable
.pipe(
bufferToggle(pauseSignal, () => resumeSignal)
);Future Directions: Async Generators
Proposed by Jafar Husain for future JavaScript (ES beyond ES7):
Combine async + generators into
async function*/yield await.Example: mouse drag expressed in a
for...onloop (a proposed syntax for iterating over observables):
async function* mouseDrags(element) {
for await (const md of fromEvent(element, 'mousedown')) {
const moves = fromEvent(document, 'mousemove')
.takeUntil(fromEvent(document, 'mouseup'));
for await (const mm of moves) {
yield { x: mm.clientX, y: mm.clientY };
}
}
}This brings the declarative power of observables into imperative syntax, offering the best of both worlds.
Key Takeaways
Asynchronous programming is hard, but abstractions like promises, observables, async/await and generators offer cleaner solutions.
Observables unify async and event handling into a composable, queryable model — treat your mouse as a database.
Backpressure is solvable (lossy, lossless, controlled).
The future includes async generators to combine declarative streams with imperative readability.
The goal: react to events, load, failure, and users — keeping applications responsive and maintainable.
"Everything is a stream."

Ask anything
We've read this whole study set, so questions about it get the best answers.