Why Sequential events.once Awaits Can Miss a Node.js Event

Both events were emitted, but the second listener arrived too late. Register waits before production, then check cancellation, repeated events and ownership.

Share
Two orange listening gates on a signal track, with a capsule passing the second gate before it opens.

Your operation emits both events, yet the second await once(...) never finishes. Before adding a delay to the producer, check when that second listener is installed. EventEmitter delivers events synchronously; resuming an async function after an await happens later. Register both one-time waits before starting the operation, then await their results together.

This is an AI-prepared, documentation-based explainer, not a personally reproduced incident. All examples and timelines are illustrative and unexecuted. See the editorial policy.

The second listener missed its appointment

Imagine a worker that announces metadata and then completion. A consumer waits for metadata, processes it, and only then starts waiting for completion. That reads like a tidy protocol. The problem is that a tidy reading order isn't a subscription schedule.

This illustrative CommonJS fragment assumes Node.js and two distinct event names. The producer deliberately emits both in the same JavaScript call stack:

const { EventEmitter, once } = require('node:events');
const bus = new EventEmitter();

async function collect() {
  const [metadata] = await once(bus, 'metadata');
  const [finished] = await once(bus, 'finished');
  return { metadata, finished };
}

const waiting = collect();
bus.emit('metadata', { job: 'example' });
bus.emit('finished', { ok: true });
// waiting still needs a future 'finished' event.

The first wait is registered when collect() begins. The metadata emission resolves that wait, but the producer continues its current stack before the consumer resumes. Completion is emitted while there is no completion listener. Later, the consumer registers one and waits for another emission. The event wasn't stored somewhere with a delivery complaint attached. Ordinary EventEmitter events aren't a replay log.

Node's multiple-event caveat documents this trap, including next-tick emissions. You don't need a mysterious network race to explain this particular example. The registration order alone is enough.

Subscribe first, consume later

For two independent notifications from one operation, create both waits up front. This illustrative replacement assumes no producer failure and no need to cancel; those boundaries come next:

const metadataWait = once(bus, 'metadata');
const finishedWait = once(bus, 'finished');
const waitingForBoth = Promise.all([metadataWait, finishedWait]);

bus.emit('metadata', { job: 'example' });
bus.emit('finished', { ok: true });

waitingForBoth.then(([metadataArgs, finishedArgs]) => {
  const [metadata] = metadataArgs;
  const [finished] = finishedArgs;
  useResults(metadata, finished); // application function
}).catch(reportFailure); // application error policy

The useful change happened before either emission: both once calls ran. Promise.all coordinates the resulting promises; it doesn't travel backwards and collect an event that was already missed. Creating it after the emissions can still work if the two waits were already installed and resolved. Creating a wait after its event cannot recover that event through Promise.all.

In application code, put the subscription setup before the call that can start producing notifications. A method named start() may emit synchronously before returning. “We'll subscribe on the next line” is a surprisingly optimistic availability strategy.

Check the protocol before parallelizing every wait

This repair assumes both event names describe results you want from the same operation. If completion could be emitted by an earlier job on a shared emitter, early subscription can collect the wrong job's result. Use an emitter scoped to the operation, correlate event payloads, or expose an operation-specific promise. Removing a registration gap doesn't establish message ownership.

Two pre-created waits for the same event name are another trap: both can resolve from the first emission. They don't automatically mean “first occurrence” and “second occurrence.” For a stream of repeated events, consider the events.on async iterator and its documented buffering and lifecycle behavior, or an explicit queue. Register the iterator before production too. Decide how it ends and how backlog is bounded; changing the waiting API doesn't supply those policies.

If processing the first event is actually required before the producer may send the next, express that handshake in the producer's protocol. A consumer's await does not, by itself, tell an EventEmitter producer to pause.

A timeout can expose the gap without fixing it

A longer timeout won't subscribe earlier. It only gives another completion emission more time to arrive, which can make a shared-emitter bug look intermittent. Trace three facts for each operation: subscription installed, event emitted, and wait settled. Include event name and operation identity. An emission log without a subscription timestamp proves very little about delivery.

Also decide what happens when the operation fails or the caller abandons the wait. Node's events.once options support an AbortSignal to cancel waiting. Promise.all rejecting isn't an instruction to cancel every other asynchronous activity. Tie remaining subscriptions to an explicit cancellation owner and handle rejections promptly; do not leave a listener waiting indefinitely after a sibling result has failed.

The earlier client-disconnect explainer covers cancellation of downstream work. Here the initial failure is different: a listener starts too late. Cleanup still matters after you correct that registration boundary.

Test the fast producer

Start with the least forgiving case: both distinct events emitted back-to-back synchronously after subscriptions are installed. Then try deferred emissions, failure between results, caller cancellation, an event that never arrives, and two overlapping operations. For a repeated event name, assert which occurrence each consumer receives. These are proposed checks, not test results from this article.

When a test times out, inspect the subscription ledger before increasing the timeout. Put the event-producing call beside the listener setup in code review. The important question is simple: who was listening when the event happened?