liveBook · Manning

Asynchronous programming

As explained in JavaScript in Depth

A mode of execution in which operations do not complete in the same immediate call sequence that initiated them.

A program can schedule five letters in one order and print them in another. The calls register work for later; they do not run each callback immediately. Which callback runs next depends on the available queues, the runtime, and how the file is loaded. section 1.1

Table 1.1 Running the same code in five different runtimes yields six different results
Runtime
Variation
Results
Node.js
CommonJS
Hello
Node.js
ECMAScript module
elHo
l
Deno
ECMAScript module
elHlo
Bun
ECMAScript module
Helo
L
Chrome
CommonJS
Error! process.nextTick does not exit.
Cloudflare Workers
ECMAScript module
eHllo

Compare the results before assuming that one runtime’s callback order is universal. Even Node.js produces different results for CommonJS and ECMAScript modules. section 1.1

The precise boundary is the call stack, not elapsed time. A synchronous callback runs while its caller remains on the stack. An asynchronous callback runs after that stack has unwound, on a new stack. It retains variables it closed over, but not its caller’s active execution context, including its try/catch block. section 8.2

Same callback shape, different context

With forEach, logging each item completes before the following `console.log('done')`. Wrap each item’s logging in `setTimeout`, and `done` prints first: the loop schedules callbacks and returns before they run. A cache-backed callback API is more treacherous. A cache hit can invoke its callback synchronously, while a miss invokes it after a fetch; an outer try/catch can therefore catch a callback error on one path but not the other. section 8.2 section 8.2

function getData(key, callback) {
  if (cache.has(key)) {
    callback(cache.get(key));  #A
  } else {
    fetchFromServer(key, (value) => {
      cache.set(key, value);
      callback(value);  #B
    });
  }
}

The two callback calls look interchangeable, but the cache-hit path shares the caller’s stack and the fetch path does not. section 8.2

Do not discard ordering as unknowable; rely on guarantees you understand. Promise continuations run as microtasks, which drain before the runtime checks the macrotask queue. Between two awaits, other promise-chain microtasks may run, but an I/O callback from another request cannot enter during that drain. This distinction matters when two awaits update related state, such as debiting and then crediting an account. section 8.5 section 8.5

Asynchrony also has a cost. A stream transform that waits for a network or database operation can pause the pipeline and propagate backpressure. Marking purely synchronous per-chunk work `async` instead adds promises, microtasks, and allocation pressure without useful waiting. A Node.js synchronous transform avoids that extra work; Web Streams retain their promise-based per-chunk cost. section 10.7.1

How JavaScript in Depth covers it

How deep it goes
Defines asynchrony through call-stack separation, then examines callback paths and queue ordering without specifying one universal runtime schedule.
Examples
Contrasts forEach with timers, cache hits with fetches, sequential awaits during a funds transfer, and synchronous with async transforms.
What it assumes
Builds the call-stack distinction from function calls while using JavaScript callbacks, timers, promises, and await in examples.
What you can do after
Diagnose/debug with it when callback timing changes error handling or output order, and avoid unnecessary async stream-transform overhead.
How it connects
Connects call stacks, closures, try/catch, event loops, microtasks, promises, backpressure, and stream transforms.

Also explained in

Compare how 37 books explain asynchronous programming →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of JavaScript in Depth. The section links point to the parts of the book it draws on.