Skip to content

late-listener ​

A listener for an event that happens once in an object's life, added after the function waited: conn.once("close", ...) after an await, on a socket the function already had. If the event came during the await, the listener waits for ever. On by default, as an error.

Why: abort on an AbortSignal, close on a Node stream or socket, open on a WebSocket, load on a page: each happens at most once, and an event that already happened isn't repeated for a listener that comes later. Nothing fails: the cleanup the listener does just never runs (a subscription stays, a timer keeps going, a request is never cancelled). Whether the event came during the await depends on timing, so tests pass and production leaks. TypeScript sees a valid call.

❌ Rejected: the client may leave while the first page is read

✕ Rejectedlate-listener
ts
import type { Socket } from "node:net";

declare function firstPage(): Promise<string>;

export async function stream(conn: Socket, unsubscribe: () => void): Promise<void> {
  conn.write(await firstPage());
  conn.once("close", unsubscribe);
}
text
`close` happens once on `Socket` (node:net), and `conn` may have had it during the `await` on
line 6: a listener added after it never runs
  = help: Add the listener before the first `await`; or test `conn.closed` after waiting, and
    handle the case where it already happened (before adding the listener, or right after)

✅ Accepted: the listener first, then the work that waits

✓ Accepted0 diagnostics
ts
import type { Socket } from "node:net";

declare function firstPage(): Promise<string>;

export async function stream(conn: Socket, unsubscribe: () => void): Promise<void> {
  conn.once("close", unsubscribe);
  conn.write(await firstPage());
}

✅ Also accepted: test what says it already happened, after the await

✓ Accepted0 diagnostics
ts
import type { Socket } from "node:net";

declare function firstPage(): Promise<string>;

export async function stream(conn: Socket, unsubscribe: () => void): Promise<void> {
  const page = await firstPage();
  if (conn.closed) return unsubscribe();
  conn.once("close", unsubscribe);
  conn.write(page);
}

The same holds for a signal: aborted while the function waited, its abort never comes again.

❌ Rejected: a cancel that never runs

✕ Rejectedlate-listener
ts
declare function prepare(): Promise<void>;
declare function cancel(): void;

export async function work(signal: AbortSignal): Promise<void> {
  await prepare();
  signal.addEventListener("abort", cancel, { once: true });
}

✅ Accepted: listen first; or stop when it is already aborted

✓ Accepted0 diagnostics
ts
declare function prepare(): Promise<void>;
declare function cancel(): void;

export async function work(signal: AbortSignal): Promise<void> {
  signal.addEventListener("abort", cancel, { once: true });
  await prepare();
}

export async function workLater(signal: AbortSignal): Promise<void> {
  await prepare();
  if (signal.aborted) return cancel();
  signal.addEventListener("abort", cancel, { once: true });
}

And a page: by the time a module that waited for its configuration adds load, the page may have loaded.

✕ Rejectedlate-listener
ts
declare function loadConfig(): Promise<void>;
declare function start(): void;

export async function boot(): Promise<void> {
  await loadConfig();
  window.addEventListener("load", start, { once: true });
}

✅ Accepted: ask the document first

✓ Accepted0 diagnostics
ts
declare function loadConfig(): Promise<void>;
declare function start(): void;

export async function boot(): Promise<void> {
  await loadConfig();
  if (document.readyState === "complete") start();
  else window.addEventListener("load", start, { once: true });
}

What counts ​

  • The events are the packs' data: events.once of the Node pack and of the browser pack (libraries), each with the test that says it already happened (signal.aborted, stream.closed, stream.readableEnded, stream.writableFinished, ws.readyState, document.readyState, worker.threadId === -1, ...), or none where the platform has none (complete on an IndexedDB transaction). Each entry is made to happen on Node, and in Chromium, Firefox and WebKit, by the packs' tests. An event that can happen again (data, message, resize, pageshow) is never reported.
  • The receiver's class is what the source writes down, read the way unknown-event reads it: through every written form of its type that calls are resolved through. A parameter or local declared with the class (req: IncomingMessage, socket: net.Socket), window, document, new WebSocket(...), a const holding what createReadStream(...) or spawn(...) returns; a loop variable (for (const socket of sockets), for (const [, socket] of byId)), an element (sockets[0], byId.get(id)?.once(...)), a destructured parameter (({ signal }: { readonly signal: AbortSignal })), a member (options.socket), a field (readonly #socket: Socket, a parameter property), an item a forEach callback is called with. A member of a platform object is the class the packs' creates give it (controller.signal of an AbortController). As a last resort, a member named signal listened to for abort is an AbortSignal when its type can't be read at all: that is the platform's name for one.
  • A listener is on, once, addListener, prependListener, prependOnceListener, addEventListener and std's listen, and a handler property set (ws.onopen = start, signal.onabort = cancel, request.onsuccess = done), the more common spelling in browser code. A callback of forEach, map, some, ... runs right away: its listeners are added where the call is.
  • Late means: on some path, the function waited (an await, a yield, a for await round) while it had the object (a parameter, something captured, this.x, a global, a local bound before the await), and didn't test it since. A test is reading one of its properties in a condition (if (conn.closed), ws.readyState === WebSocket.OPEN, !signal.aborted), passing it to a function in a condition (if (isClosed(ws))), or signal.throwIfAborted() (also inside unsafe(() => ...), as the arrow's body or its one statement); one right after adding the listener counts too (signal.addEventListener( "abort", stop); if (signal.aborted) stop();). A branch that tests it doesn't help the paths that don't.
  • Fine: an object made after the await (const ws = new WebSocket(url)): nothing happened to it yet. A local that names an object the function had (const socket = this.socket, AbortSignal.any([signal]), born aborted when one of them is, a loop variable) is that object.
  • A controller made here and kept: const controller = new AbortController() whose controller nothing outside reached before the listener (it wasn't passed, stored, returned, captured by a callback, or aborted: only its signal was read). Only code holding a controller can abort its signal, and none did. A WebSocket or a child process made here acts on its own: it stays reported.
  • A callback that runs later (a timer, .then, another listener: what the flow layer knows runs later) is the same as an await for what it captured: res.once("finish", () => req.once("end", ...)) adds end after the response finished, and the request may have ended before that.
  • A call that waits with the object (await handshake(worker)) watches it when that function listens for the same event on that parameter itself (worker.once("exit", ...) inside handshake): an exit during the await is its to handle, so the listener after it is fine. Through a function that doesn't (await finished(stream)), it still counts.

What the rule can't see ​

  • The program's own emitters. A class of the project that extends EventEmitter, or a plain new EventEmitter(), has no data: which of its events happen once is the program's to say, and there is no way to declare it (the packs' events describe platform classes). Use a promise for a one-time event of your own (closed: Promise<void>): awaiting a settled promise still works.
  • A receiver whose class the source doesn't write down: what a library function or a platform method returns (store.put(...)'s IDBRequest, unless it is declared: const put: IDBRequest<IDBValidKey> = store.put(...)), the parameters of a callback a library calls (createServer((req, res) => ...)), a member of a platform object the packs' creates don't list (child.stdout). The ws package's sockets: its pack lists no events yet.
  • events.once(emitter, name) and other functions that add a listener for you (other than std's listen): a promise that never settles after the event happened is promise-never-settles's question, inside the function that makes it.
  • A listener added synchronously to an object that arrives already done (a function called with an aborted signal): no await in the function, so nothing says time passed.
  • A test through a local (const done = conn.closed; ... if (done)): only a test of the object itself counts.

MIT OR Apache-2.0 · Docs by Gemini 4 Neon Extra