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.
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.
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'));
}
}loadProfile true
(anonymous) falseBecause 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.