Skip to content
jshacks.dev
Async

Name your async functions for better stack traces

Name your async functions for better stack traces in JavaScript: V8 prints at async name for named functions and only a location for anonymous ones.

1 min read
Summarize in AI

When an error crosses an await, V8 rebuilds the stack from the async functions waiting on it. A function with a name shows up by name; an anonymous one shows up as a file position.

JavaScript
const delay = (ms) => new Promise((r) => setTimeout(r, ms));

const loadUser = async () => {
  await delay(1);
  throw new Error('boom');
};

const named = async function loadProfile() {
  await loadUser();
};
const anonymous = [
  async () => {
    await loadUser();
  },
][0];

for (const fn of [named, anonymous]) {
  try {
    await fn();
  } catch (err) {
    console.log(fn.name || '(anonymous)', err.stack.includes('at async loadProfile'));
  }
}
Text
loadProfile true
(anonymous) false

Because loadUser awaits, the error is thrown after the original call has returned, so a plain stack would show only the timer. The engine stitches in an at async frame for each function awaiting the one that failed. See the V8 blog post on async stack traces. The anonymous arrow in an array element has no inferred name, so its frame carries only a path and line number.

A variable assignment gives an arrow function an inferred name, as loadUser shows. Callbacks passed inline, such as items.map(async (x) => ...), stay anonymous. Pull them out and name them when you debug.

Also inDebugging
Taggednode 24
Share

More snippets

Debugging

Group related logs with console.group

Indent related console output under a label with console.group and console.groupEnd, so interleaved logs from one request stay readable in Node.js 24.

1 min read
Async

Sleep for a number of milliseconds

Sleep for a number of milliseconds in JavaScript with a promise around setTimeout, or timers/promises in Node.js 24, and await it.

1 min read
Node.js

Read a text file with fs promises

Read a text file with fs promises in Node.js: await readFile with an encoding, and catch the error code when the file is missing. Node.js 24.

1 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.