Skip to content
jshacks.dev
Async

Async Stack Traces and How Engines Build Them

Learn why stack traces lose their callers after an await, how V8 rebuilds async stack traces from promise chains and how to keep useful traces in your own code.

7 min read
Summarize in AI
Flat illustration of jobs on a conveyor heading to a rack of workers, with the JavaScript, Google Chrome and Apache Kafka logos.

A synchronous stack trace is a record of who called whom, taken from the call stack at the moment an error was created. After an await, that stack is gone. The function that called you has already returned, and the continuation is running from the microtask queue with an almost empty stack. If engines did nothing about this, every error thrown after an await would show one line, the function that threw it, and no clue which request or caller led there. V8 does something about it, in both Chrome and Node.js, by reconstructing the missing frames from the chain of promises that are waiting on each other. This post explains what a trace looks like with and without that help on Node.js 24, shows the rules for when the reconstruction works and when it breaks, and gives practical advice for keeping traces useful in your own code, including Error causes and the stack size limit.

The problem: a stack that ends early

Here is a call chain that crosses an await, and the trace of the error at the bottom.

JavaScript
async function readConfig() {
  await Promise.resolve();
  throw new Error("config missing");
}

async function startServer() {
  await readConfig();
}

async function main() {
  await startServer();
}

try {
  await main();
} catch (error) {
  console.log(error.stack.split("\n").slice(0, 4).join("\n"));
}
Text
Error: config missing
    at readConfig (file:///app/main.mjs:3:9)
    at async startServer (file:///app/main.mjs:7:3)
    at async main (file:///app/main.mjs:11:3)

The first frame, readConfig, is a real frame. It was running when the error was created. The next two are marked async. They are not on the stack at all, because startServer and main were suspended at their await. V8 inferred them from the fact that startServer is waiting on the promise that readConfig returned, and main is waiting on the one from startServer. The path and the line numbers shown are examples, and your trace shows your own file locations.

How V8 builds the async frames

Each async function that is suspended at an await is attached to the promise it is waiting on. When an error is created inside a running function, V8 walks the current stack for the real frames, then looks at the promise the current function will resolve and finds whichever function is awaiting it, and then that function's promise, and so on. Each hop adds an at async name line. The feature is called zero-cost async stack traces, because it uses information the engine already keeps for promises instead of recording extra data on every call. It has been on by default since V8 7.3, which is in Chrome 73 and Node.js 12.

The walk follows one kind of link only: a function that is directly awaiting the promise of another async function.

When the chain breaks

Any step that does not use await on an async function's promise cuts the walk.

JavaScript
function legacyWrapper() {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      readConfig().then(resolve, reject);
    }, 1);
  });
}

async function main() {
  await legacyWrapper();
}

try {
  await main();
} catch (error) {
  console.log(error.stack.split("\n").slice(0, 4).join("\n"));
}
Text
Error: config missing
    at readConfig (file:///app/main.mjs:3:9)

The trace shows one frame. readConfig was called from a timer callback, so there is no await linking it to main, and the connection between them goes through a new Promise and then(resolve, reject), which the engine does not follow. The caller is lost. The rule of thumb is that async frames survive only along await chains between async functions.

Other breakers:

  • Promise.all, Promise.race and the other combinators. A function awaiting Promise.all([a(), b()]) appears in the trace of an error from a, since V8 handles all specially, but custom combinators and promise libraries do not.

  • then chains with callbacks that are not async functions.

  • Callbacks fired by event emitters, timers and I/O. They start a new stack with no history.

  • Thenables from other libraries and code transpiled to generators or older promise implementations.

What the real stack gives you

An Error captures its trace when it is constructed, not when it is thrown. That matters when you create an error in one place and reject with it somewhere else.

JavaScript
function makeError(message) {
  return new Error(message);
}

async function run() {
  const error = makeError("created far from the failure");
  await Promise.resolve();
  throw error;
}

try {
  await run();
} catch (caught) {
  console.log(caught.stack.split("\n")[1].trim().startsWith("at makeError"));
}
Text
true

The trace begins at makeError, where the error was created, so the line that threw it is not shown. If you build errors in a helper, the helper becomes the top frame and the useful context, the caller, may be missing or pushed down. Error.captureStackTrace(this, constructorOpt) lets a custom error class or helper omit its own frames.

JavaScript
class AppError extends Error {
  constructor(message) {
    super(message);
    this.name = "AppError";
    Error.captureStackTrace?.(this, AppError);
  }
}

function fail() {
  throw new AppError("bad state");
}

try {
  fail();
} catch (error) {
  console.log(error.stack.split("\n")[1].trim().startsWith("at fail"));
}
Text
true

Error.captureStackTrace is a V8 API, so the optional call keeps the code working in other engines, where the standard stack property is still filled in by the engine.

Wrapping errors without losing the original

When you catch an error and throw another, pass the original as the cause. Node.js and current browsers print the cause chain, and each error keeps its own stack.

JavaScript
async function loadUser(id) {
  try {
    await Promise.reject(new Error("connection reset"));
  } catch (cause) {
    throw new Error(`could not load user ${id}`, { cause });
  }
}

try {
  await loadUser(7);
} catch (error) {
  console.log(error.message);
  console.log("cause:", error.cause.message);
}
Text
could not load user 7
cause: connection reset

A bare throw new Error("could not load user") inside catch discards the first stack, which is often the only one that contains the failing frame. Always attach it.

The stack size limit

V8 keeps only the top ten frames by default. In a deep async chain, the bottom of the trace is cut.

JavaScript
console.log(Error.stackTraceLimit);

Error.stackTraceLimit = 50;

console.log(Error.stackTraceLimit);
Text
10
50

Raising the limit costs a little time and memory for each error created, since it captures more frames. A server that creates many errors on a hot path may want to keep the default and raise it only during debugging, or set it from the command line with --stack-trace-limit=50. Node.js also offers --async-stack-traces, which is on by default, for the feature in this post, and --enable-source-maps so that traces from bundled or TypeScript code point to the original source lines.

Making your own code easier to debug

**Use async and await consistently along important paths.** A function that returns promise.then(...) instead of awaiting loses an async frame, because the function has already finished. Declaring the function async and using await keeps it in the trace.

JavaScript
// loses a frame: the function is not suspended while the work runs
function loadSettings() {
  return readConfig().then((config) => config);
}

// keeps its frame
async function loadSettingsAsync() {
  return await readConfig();
}

The second form costs one extra microtask and shows up in the trace, a good trade for code paths where you value traces. It is also what makes return await inside try blocks worthwhile, as covered in the post on how async functions return promises.

Name functions. An anonymous arrow function appears as <anonymous>, which tells you little. Giving callbacks names, or assigning arrows to variables that name them, makes traces readable.

Add context at boundaries. At the edge of a subsystem, wrap errors with a message that names the operation and the inputs, and attach the cause. The trace tells you where, and the message tells you what you were doing.

Capture a stack at the call site when you cannot await. For code that schedules work in a callback, create an Error when you schedule it and use its stack in later reports, which restores the missing caller.

JavaScript
function scheduleJob(job) {
  const scheduledAt = new Error("job scheduled here");

  setTimeout(async () => {
    try {
      await job();
    } catch (error) {
      error.scheduledAt = scheduledAt.stack;
      throw error;
    }
  }, 1);
}

This costs the creation of one error per scheduled job, which is a fair price for a queue that matters and too much for one that handles millions of tiny items.

What other engines do

Firefox and Safari show async frames in the developer tools for async functions, and the formats of the stack string differ between engines, since there is no standard for it. The stack property is not in the ECMAScript specification, and a proposal to standardize it is still in progress. Do not parse it for logic. Treat it as text for people, and use structured fields for anything a program must read.

Also inDebugging
Share

Keep reading

Flat illustration of an editor window full of code, with the Google Chrome, JavaScript and npm logos.
Browser

script Tags: async, defer and type=module

Compare classic, async, defer and module script tags: when each downloads, when each runs, how order is kept and which one to pick for each kind of script.

6 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.