Backend developer checking async Node.js EventEmitter handler completion before releasing a shared resource.

Finish Async EventEmitter Handlers Before Releasing Resources

Thu, Dec 3, 2026

The operational question is not whether an EventEmitter listener was registered, called, or even free of errors. It is whether every required handler has finished the asynchronous work that still owns a shared resource before that resource is released. I treat that as an interface-completion problem. The decisive counterexample is deliberately uneventful: alpha and beta are already registered, both listeners enter, emit() returns, no handler has failed, and both remain blocked behind explicit gates. The application still cannot close the resource because invocation is not completion.

This article builds a local CommonJS fixture around that boundary. The fixed operation has two required handlers, two independent gates, a synthetic open/closed resource, explicit entered and completed acknowledgements, per-handler receipts, and a sequence ledger. I use Node.js v22.14.0 only as an archived documentation reference; I do not present it as the latest Node.js release or as a patch recommendation. No fixture execution was performed for this article, so every laboratory outcome is EXPECTED / NOT EXECUTED. If you later run the file, record the actual runtime and actual output separately rather than substituting them for the design.

The repair is intentionally small: an application-owned registry for business handlers whose returned native promises cover all resource-owning work. The operation owner can then decide among COMPLETE, FAILED_AFTER_DRAIN, REPAIR_RETURN_CONTRACT, BLOCK_CONFIGURATION, and HOLD_INFLIGHT. Those are article-defined decisions, not Node.js API values.

Define the work that owns the resource

Before looking at emit(), I define the operation that must become complete. The required-handler manifest is frozen as ['alpha', 'beta']; the operation ID is a fixed value such as op-001; and both handlers are allowed to access one synthetic resource while it is open. A successful receipt has exactly the application fields { operationId, handlerId, status: 'ok' }. Acceptance requires one valid receipt from each required ID and no unexpected receipt.

That definition matters because “the event was emitted” is too weak a release rule. The resource owner needs a finite manifest of work that can still touch the resource. The handler owner needs a contract saying that the promise returned by its handler does not settle until all resource access owned by that handler is finished. The operation owner needs to know which handlers are mandatory for this operation. Only after those contracts agree can the resource owner authorize close.

This article assumes both listeners are already installed and have entered before the key checkpoint. Registration coverage is therefore intentionally out of scope. If the problem is whether waits were installed before a producer burst, the neighboring Refonte Learning article on how to register event waits before emission addresses that different failure mode. Here there is no missed subscription, replay issue, or events.once() race to repair.

My success rule is stricter: every required handler must be terminal, every fulfilled handler must return the exact receipt shape for the same immutable operation ID, every owned access must occur before close, and close must be recorded exactly once. Anything less is evidence for holding or repairing the interface, not for releasing the resource.

I also assume a single in-process operation with no hidden transport, database, HTTP, retry, or distributed-delivery semantics. That narrowness is useful: it isolates the interface question from unrelated durability concerns. The synthetic resource is intentionally simple because its only job is to make lifetime ownership visible. Likewise, alpha and beta are business identities, not listener indexes. If a future implementation changes registration order, the required manifest still names the same participants. This keeps the acceptance rule stable under ordinary refactoring and forces reviewers to reason about declared ownership instead of incidental array position.

One more assumption is explicit: the operation owner already knows that exactly two handlers are required. The registry does not attempt discovery from EventEmitter. If the application cannot declare its required participants, then it cannot prove this two-handler completion condition with the method shown here. In that situation the correct decision is to hold or redesign the ownership boundary, not to infer completeness from whatever callbacks happened to run.

Read the EventEmitter completion boundary

The archived Node.js v22.14.0 Events documentation says that EventEmitter calls listeners synchronously in registration order. That tells us when invocation occurs, not when asynchronous work inside an async listener later settles. The same documentation defines emitter.emit() as returning true when the event had listeners and false otherwise; it does not define that Boolean as an aggregate of listener return values or promise settlements.

An async listener begins synchronously until it reaches an await point. At that point it has already been invoked, but the promise representing its eventual completion may remain pending. emit() does not hand the caller that promise inventory. Consequently, await emitter.emit('work', ctx) simply awaits the Boolean returned by emit(). Since a Boolean is not a promise for the listeners' asynchronous work, the expression resumes without joining either listener. That is a direct consequence of the documented return contract, not an event-loop trick.

captureRejections addresses a different concern. With the option enabled, Node.js attaches rejection handling to listener promises and routes a rejection to the configured rejection hook or 'error' path. The documentation explicitly describes automatic capture of promise rejection; it does not turn emit() into a work join.

That distinction is easy to blur because other event APIs also expose synchronous dispatch results. Refonte Learning's article on DOM dispatch cancellation and listener results examines a browser contract where cancellation and listener outcomes must not be conflated. I do not import DOM cancellation semantics into Node.js here; the useful comparison is only that a dispatch return value must be read according to its own documented interface.

Build a deterministic two-handler fixture

The fixture uses one local .cjs file, native promises, node:events, node:assert/strict, plain JavaScript records, and no external services. Every case creates fresh state so no listener, gate, receipt, error, resource flag, or sequence number leaks into the next case. alpha and beta each receive a dedicated deferred gate. They acknowledge entry before awaiting that gate and acknowledge completion in a finally block, so the harness can distinguish “invoked,” “still pending,” and “terminal” without guessing from elapsed time.

The synthetic resource exposes only access(handlerId, operationId) and close(). Every access attempt is recorded with a monotonically increasing sequence number, the handler identity, the operation identity, and whether the resource was open at the moment of access. If code accesses after close, the ledger still records the attempted access and then throws. close() records its own sequence number and rejects a second close. That design makes premature release observable rather than silently hiding it.

The EventEmitter harness has a test-only ownership layer that stores each listener's original returned promise. That inventory exists because the wrapper explicitly retains it; EventEmitter did not return it. The harness also owns every .then() observer promise it creates, and it keeps the original potentially rejected promise for later Promise.allSettled() inspection instead of converting failures into fulfilled .catch() results.

The complete fixture appears below. It is intentionally application-sized rather than a replacement EventEmitter or a generic emitAsync package.

// eventemitter-completion.cjs
'use strict';

const assert = require('node:assert/strict');
const { EventEmitter } = require('node:events');

const OPERATION_ID = 'op-001';
const REQUIRED = Object.freeze(['alpha', 'beta']);
const DECISION = Object.freeze({
  COMPLETE: 'COMPLETE',
  FAILED_AFTER_DRAIN: 'FAILED_AFTER_DRAIN',
  REPAIR_RETURN_CONTRACT: 'REPAIR_RETURN_CONTRACT',
  BLOCK_CONFIGURATION: 'BLOCK_CONFIGURATION',
  HOLD_INFLIGHT: 'HOLD_INFLIGHT',
});

function deferred() {
  let resolve;
  let reject;
  const promise = new Promise((res, rej) => {
    resolve = res;
    reject = rej;
  });
  return { promise, resolve, reject };
}

function freshState() {
  let seq = 0;
  const ledger = [];
  const receipts = [];
  const errors = [];
  const gates = { alpha: deferred(), beta: deferred() };
  const entered = { alpha: deferred(), beta: deferred() };
  const completed = { alpha: deferred(), beta: deferred() };

  function record(event) {
    const row = { ...event, seq: ++seq };
    ledger.push(row);
    return row;
  }

  const resource = {
    open: true,
    closeCount: 0,

    access(handlerId, operationId) {
      const event = record({
        type: 'access',
        handlerId,
        operationId,
        open: this.open,
      });

      if (!this.open) {
        throw new Errorresource closed for ${handlerId});
      }

      return event;
    },

    close() {
      if (this.closeCount !== 0) {
        throw new Error('resource closed twice');
      }

      this.closeCount += 1;
      this.open = false;
      return record({ type: 'close' });
    },
  };

  return {
    ledger,
    receipts,
    errors,
    gates,
    entered,
    completed,
    resource,
    record,
  };
}

function receipt(handlerId) {
  return {
    operationId: OPERATION_ID,
    handlerId,
    status: 'ok',
  };
}

function makeHandler(state, handlerId, options = {}) {
  return async function ownedBusinessHandler() {
    state.record({ type: 'entered', handlerId });
    state.entered[handlerId].resolve();

    try {
      await state.gates[handlerId].promise;

      if (options.reject) {
        const err = new Error${handlerId}-failure);
        err.handlerId = handlerId;
        throw err;
      }

      state.resource.access(handlerId, OPERATION_ID);

      const value = receipt(handlerId);
      state.receipts.push(value);
      state.record({ type: 'receipt', handlerId });
      return value;
    } finally {
      state.record({ type: 'completed', handlerId });
      state.completed[handlerId].resolve();
    }
  };
}

function makeEmitterHarness(state, handlers, captureRejections = false) {
  const emitter = new EventEmitter({ captureRejections });
  const originals = new Map();
  const observerChains = [];
  const errorObserved = deferred();

  if (captureRejections) {
    emitter[Symbol.for('nodejs.rejection')] = (err, eventName) => {
      // Synchronous and nonthrowing by fixture policy.
      state.errors.push({
        handlerId: err && err.handlerId,
        message: err && err.message,
        eventName,
      });

      errorObserved.resolve();
    };
  }

  for (const id of REQUIRED) {
    emitter.on('work', () => {
      const original = handlers[id]();
      originals.set(id, original);

      const observer = original.then(
        value => ({ id, status: 'fulfilled', value }),
        reason => ({ id, status: 'rejected', reason }),
      );

      observerChains.push(observer);
      return original;
    });
  }

  return {
    emitter,
    originals,
    observerChains,
    errorObserved,
  };
}

function validateRegistry(entries) {
  const ids = entries.map(entry => entry.id);

  assert.equal(entries.length, REQUIRED.length);
  assert.deepStrictEqual([...ids].sort(), [...REQUIRED].sort());
  assert.equal(new Set(ids).size, ids.length);

  for (const entry of entries) {
    assert.equal(typeof entry.run, 'function');
  }
}

function validateReceipt(value, id) {
  assert.deepStrictEqual(value, {
    operationId: OPERATION_ID,
    handlerId: id,
    status: 'ok',
  });
}

function startOwnedRegistry(state, entries) {
  validateRegistry(entries); // Must pass before any handler is invoked.

  const originals = entries.map(({ id, run }) => {
    const promise = run();

    assert.ok(
      promise instanceof Promise,
      ${id} must return a native Promise,
    );

    return { id, promise };
  });

  const settled = Promise
    .allSettled(originals.map(item => item.promise))
    .then(results => {
      let failed = false;

      for (let i = 0; i < results.length; i += 1) {
        const result = results[i];
        const id = originals[i].id;

        if (result.status === 'fulfilled') {
          validateReceipt(result.value, id);
        } else {
          failed = true;
        }
      }

      state.resource.close();

      return {
        decision: failed
          ? DECISION.FAILED_AFTER_DRAIN
          : DECISION.COMPLETE,
        results,
      };
    });

  return { originals, settled };
}

function evidenceAccepts(state) {
  const completedIds = state.ledger
    .filter(event => event.type === 'completed')
    .map(event => event.handlerId)
    .sort();

  assert.deepStrictEqual(
    completedIds,
    [...REQUIRED].sort(),
  );

  assert.equal(state.resource.closeCount, 1);

  const close = state.ledger.find(
    event => event.type === 'close',
  );

  const acceptedAccesses = state.ledger.filter(
    event => event.type === 'access' && event.open,
  );

  assert.ok(acceptedAccesses.length >= 2);
  assert.ok(
    acceptedAccesses.every(event => event.seq < close.seq),
  );

  return true;
}

async function caseN01() {
  const state = freshState();

  const handlers = {
    alpha: makeHandler(state, 'alpha'),
    beta: makeHandler(state, 'beta'),
  };

  const harness = makeEmitterHarness(state, handlers);
  const emitted = harness.emitter.emit('work');

  await Promise.all([
    state.entered.alpha.promise,
    state.entered.beta.promise,
  ]);

  assert.equal(emitted, true);
  assert.equal(state.receipts.length, 0);
  assert.equal(state.resource.open, true);

  // Drain test-owned work after the checkpoint.
  state.gates.alpha.resolve();
  state.gates.beta.resolve();

  await Promise.allSettled([
    ...harness.originals.values(),
  ]);

  await Promise.all(harness.observerChains);
  return state;
}

async function caseN02() {
  const state = freshState();

  const handlers = {
    alpha: makeHandler(state, 'alpha'),
    beta: makeHandler(state, 'beta'),
  };

  const harness = makeEmitterHarness(state, handlers);
  const emitted = await harness.emitter.emit('work');

  await Promise.all([
    state.entered.alpha.promise,
    state.entered.beta.promise,
  ]);

  assert.equal(emitted, true);
  assert.equal(state.receipts.length, 0);

  state.gates.alpha.resolve();
  state.gates.beta.resolve();

  await Promise.allSettled([
    ...harness.originals.values(),
  ]);

  await Promise.all(harness.observerChains);
  return state;
}

async function caseN03() {
  const state = freshState();

  const harness = makeEmitterHarness(state, {
    alpha: makeHandler(state, 'alpha'),
    beta: makeHandler(state, 'beta'),
  });

  harness.emitter.emit('work');

  await Promise.all([
    state.entered.alpha.promise,
    state.entered.beta.promise,
  ]);

  state.gates.alpha.resolve();
  await state.completed.alpha.promise;

  assert.deepStrictEqual(
    state.receipts,
    [receipt('alpha')],
  );

  assert.equal(state.resource.open, true);

  state.gates.beta.resolve();

  await Promise.allSettled([
    ...harness.originals.values(),
  ]);

  await Promise.all(harness.observerChains);
  return state;
}

async function caseN04() {
  const state = freshState();

  const harness = makeEmitterHarness(state, {
    alpha: makeHandler(state, 'alpha'),
    beta: makeHandler(state, 'beta'),
  });

  harness.emitter.emit('work');

  await Promise.all([
    state.entered.alpha.promise,
    state.entered.beta.promise,
  ]);

  state.gates.beta.resolve();
  await state.completed.beta.promise;

  state.gates.alpha.resolve();
  await state.completed.alpha.promise;

  assert.deepStrictEqual(
    state.receipts.map(value => value.handlerId),
    ['beta', 'alpha'],
  );

  await Promise.allSettled([
    ...harness.originals.values(),
  ]);

  await Promise.all(harness.observerChains);
  return state;
}

async function caseN05() {
  const state = freshState();

  const harness = makeEmitterHarness(
    state,
    {
      alpha: makeHandler(state, 'alpha'),
      beta: makeHandler(state, 'beta'),
    },
    true,
  );

  harness.emitter.emit('work');

  await Promise.all([
    state.entered.alpha.promise,
    state.entered.beta.promise,
  ]);

  assert.deepStrictEqual(state.errors, []);
  assert.equal(state.receipts.length, 0);

  state.gates.alpha.resolve();
  state.gates.beta.resolve();

  await Promise.allSettled([
    ...harness.originals.values(),
  ]);

  await Promise.all(harness.observerChains);
  return state;
}

async function caseN06() {
  const state = freshState();

  const harness = makeEmitterHarness(
    state,
    {
      alpha: makeHandler(
        state,
        'alpha',
        { reject: true },
      ),
      beta: makeHandler(state, 'beta'),
    },
    true,
  );

  harness.emitter.emit('work');

  await Promise.all([
    state.entered.alpha.promise,
    state.entered.beta.promise,
  ]);

  state.gates.alpha.resolve();
  await harness.errorObserved.promise;

  assert.deepStrictEqual(
    state.errors,
    [{
      handlerId: 'alpha',
      message: 'alpha-failure',
      eventName: 'work',
    }],
  );

  assert.equal(
    state.receipts.some(
      value => value.handlerId === 'beta',
    ),
    false,
  );

  state.gates.beta.resolve();

  await Promise.allSettled([
    ...harness.originals.values(),
  ]);

  await Promise.all(harness.observerChains);
  return state;
}

async function caseN07() {
  const state = freshState();

  const entries = [
    {
      id: 'alpha',
      run: makeHandler(state, 'alpha'),
    },
    {
      id: 'beta',
      run: makeHandler(state, 'beta'),
    },
  ];

  const run = startOwnedRegistry(state, entries);

  await Promise.all([
    state.entered.alpha.promise,
    state.entered.beta.promise,
  ]);

  let registryDone = false;

  const observer = run.settled.then(() => {
    registryDone = true;
  });

  state.gates.alpha.resolve();
  await state.completed.alpha.promise;

  assert.equal(registryDone, false);
  assert.equal(state.resource.open, true);

  state.gates.beta.resolve();

  const result = await run.settled;
  await observer;

  assert.equal(
    result.decision,
    DECISION.COMPLETE,
  );

  assert.equal(
    evidenceAccepts(state),
    true,
  );

  return state;
}

async function caseN08() {
  const state = freshState();

  const entries = [
    {
      id: 'alpha',
      run: makeHandler(
        state,
        'alpha',
        { reject: true },
      ),
    },
    {
      id: 'beta',
      run: makeHandler(state, 'beta'),
    },
  ];

  const run = startOwnedRegistry(state, entries);

  await Promise.all([
    state.entered.alpha.promise,
    state.entered.beta.promise,
  ]);

  state.gates.alpha.resolve();
  await state.completed.alpha.promise;

  assert.equal(state.resource.open, true);

  state.gates.beta.resolve();

  const result = await run.settled;

  assert.equal(
    result.decision,
    DECISION.FAILED_AFTER_DRAIN,
  );

  assert.equal(
    state.resource.closeCount,
    1,
  );

  return state;
}

async function caseN09() {
  const state = freshState();
  const childGate = deferred();
  const detached = [];

  async function defectiveAlpha() {
    state.record({
      type: 'entered',
      handlerId: 'alpha',
    });

    state.entered.alpha.resolve();

    const child = (async () => {
      await childGate.promise;
      state.resource.access(
        'alpha',
        OPERATION_ID,
      );
    })();

    detached.push(child); // Test-only independent ownership.

    const value = receipt('alpha');

    state.receipts.push(value);
    state.record({
      type: 'receipt',
      handlerId: 'alpha',
    });

    state.record({
      type: 'completed',
      handlerId: 'alpha',
    });

    state.completed.alpha.resolve();

    return value;
  }

  const run = startOwnedRegistry(
    state,
    [
      {
        id: 'alpha',
        run: defectiveAlpha,
      },
      {
        id: 'beta',
        run: makeHandler(state, 'beta'),
      },
    ],
  );

  await Promise.all([
    state.entered.alpha.promise,
    state.entered.beta.promise,
  ]);

  state.gates.beta.resolve();

  const naive = await run.settled;

  assert.equal(
    naive.decision,
    DECISION.COMPLETE,
  );

  assert.equal(
    state.resource.open,
    false,
  );

  childGate.resolve();

  const detachedResult =
    await Promise.allSettled(detached);

  assert.equal(
    detachedResult[0].status,
    'rejected',
  );

  assert.match(
    detachedResult[0].reason.message,
    /resource closed/,
  );

  // Fresh repaired variant:
  // the returned promise includes the child.
  const repaired = freshState();
  const repairedChildGate = deferred();

  async function repairedAlpha() {
    repaired.record({
      type: 'entered',
      handlerId: 'alpha',
    });

    repaired.entered.alpha.resolve();

    await repairedChildGate.promise;

    repaired.resource.access(
      'alpha',
      OPERATION_ID,
    );

    const value = receipt('alpha');

    repaired.receipts.push(value);

    repaired.record({
      type: 'receipt',
      handlerId: 'alpha',
    });

    repaired.record({
      type: 'completed',
      handlerId: 'alpha',
    });

    repaired.completed.alpha.resolve();

    return value;
  }

  const repairedRun = startOwnedRegistry(
    repaired,
    [
      {
        id: 'alpha',
        run: repairedAlpha,
      },
      {
        id: 'beta',
        run: makeHandler(
          repaired,
          'beta',
        ),
      },
    ],
  );

  await Promise.all([
    repaired.entered.alpha.promise,
    repaired.entered.beta.promise,
  ]);

  repairedChildGate.resolve();
  repaired.gates.beta.resolve();

  const fixed = await repairedRun.settled;

  assert.equal(
    fixed.decision,
    DECISION.COMPLETE,
  );

  assert.equal(
    evidenceAccepts(repaired),
    true,
  );

  return {
    defective: state,
    repaired,
    decision: DECISION.REPAIR_RETURN_CONTRACT,
  };
}

async function caseN10() {
  const missing = freshState();

  await assert.rejects(async () => {
    startOwnedRegistry(
      missing,
      [
        {
          id: 'alpha',
          run: makeHandler(
            missing,
            'alpha',
          ),
        },
      ],
    );
  });

  assert.equal(
    missing.ledger.length,
    0,
  );

  const duplicate = freshState();

  await assert.rejects(async () => {
    startOwnedRegistry(
      duplicate,
      [
        {
          id: 'alpha',
          run: makeHandler(
            duplicate,
            'alpha',
          ),
        },
        {
          id: 'alpha',
          run: makeHandler(
            duplicate,
            'alpha',
          ),
        },
      ],
    );
  });

  assert.equal(
    duplicate.ledger.length,
    0,
  );

  return DECISION.BLOCK_CONFIGURATION;
}

async function main() {
  // Designed case inventory.
  // Running this file creates actual observations;
  // this article itself records only
  // EXPECTED / NOT EXECUTED outcomes.
  for (const fn of [
    caseN01,
    caseN02,
    caseN03,
    caseN04,
    caseN05,
    caseN06,
    caseN07,
    caseN08,
    caseN09,
    caseN10,
  ]) {
    await fn();
  }
}

if (require.main === module) {
  main().catch(err => {
    console.error(err);
    process.exitCode = 1;
  });
}

Run it locally with an explicitly recorded runtime:

node --version
node eventemitter-completion.cjs

Do not replace the first command's output with the archived documentation version. A documentation header proves which reference is being read, not which executable ran the fixture. In this article, no actual runtime manifest, digest, timing, or PASS result exists because the fixture was not executed.

Use gates rather than elapsed-time assumptions

A gate gives the case a causal checkpoint. entered.alpha.promise resolves because alpha executed up to the gate; completed.alpha.promise resolves only from alpha's terminal finally. The same structure exists independently for beta. No setTimeout(..., 10) is used to infer that a handler “must be done by now.” That would turn machine load into part of the proof.

A bounded watchdog is acceptable only as a laboratory escape hatch. If one were added around a case, expiration would mean HOLD_INFLIGHT: the harness failed to establish terminal ownership within the bound. It would not mean success, automatic cancellation, or permission to close. After an unsafe checkpoint, the harness still drains every promise it owns before the case ends, including the detached child in N09. That cleanup is for test isolation; it does not retroactively make a premature application decision safe.

returnfromemit

Return from emit while both handlers are pending

N01 is the central witness because nothing has failed. The emitter has both listeners. The synchronous invocation path reaches alpha and then beta. Each records an entered acknowledgement and stops at its own closed gate. emit('work') returns true. At the checkpoint, there are zero receipts, zero completion acknowledgements, no errors, and the resource is still open because both handlers will need it after their gates open.

Every observation in the following table is EXPECTED / NOT EXECUTED. The table states the fixture design, not captured runtime output.

N01 checkpoint

Expected state

Operational meaning

Listener registration

alpha and beta present

Subscription is not the issue

Entered acknowledgements

alpha = yes, beta = yes

Both handlers have begun

emit() return

true

The event had listeners

Gates

alpha closed, beta closed

Both returned promises remain pending

Completion acknowledgements

alpha = no, beta = no

Neither handler is terminal

Error ledger

empty

No failure evidence exists

Resource

open

Both handlers still own future access

Release decision

HOLD_INFLIGHT

Close is not yet authorized

This is enough to reject a notification-as-completion design. The argument does not depend on rejection timing, unhandled-rejection behavior, or cancellation. If the caller closes immediately after the Boolean, the later resource access by alpha or beta occurs after the resource owner has already acted on incomplete evidence. The bug is therefore present on the all-success path.

The strong debugging question is not “did the listener run?” Both did. It is “which interface can produce a terminal result for every required handler's returned work?” Plain emit() cannot answer that because its documented result says only whether listeners existed.

Awaiting the Boolean does not join the handlers

N02 changes only the caller expression to await emitter.emit('work'). The expected result is still true, and the two completion acknowledgements are still absent while both gates remain closed. The reason is mechanical: JavaScript evaluates emitter.emit(...) first, obtaining a Boolean under the Node.js contract, and then await operates on that value. It does not acquire listener promises that the API never returned.

The oracle is not a console line saying “await finished.” The oracle is the unchanged state: both entered acknowledgements exist, both completion acknowledgements do not, the receipt ledger is empty, and the resource must remain open. N02 is therefore also HOLD_INFLIGHT at the checkpoint. Adding await can make source code look more deliberate while changing none of the ownership semantics.

Observe one completion while the resource stays open

N03 releases only alpha. The fixture waits for alpha's explicit completion acknowledgement rather than assuming that resolving the gate instantly means the handler has finished. Alpha then accesses the resource while it is open, produces { operationId: 'op-001', handlerId: 'alpha', status: 'ok' }, records its terminal marker, and resolves the alpha completion acknowledgement. Beta remains behind its closed gate.

At that point alpha's receipt is useful evidence, but it is not the operation's completion proof. The required manifest contains two identities. One correct receipt establishes only that alpha fulfilled its contract. Beta is still an identified owner of future resource work, so the resource stays open and the release decision remains HOLD_INFLIGHT.

This distinction is important in production debugging because partial success often looks reassuring. A log may show that one handler completed and even include the correct operation ID. If the release rule is “I saw a successful handler,” it is under-specified. The correct question is whether the evidence covers the entire required manifest. In this fixture, the absence of beta is not interpreted as failure, success, or optionality. It is unresolved ownership.

The receipt schema also prevents a subtler mistake: accepting a structurally valid result that belongs to another operation. Each receipt is matched to both handlerId and immutable operationId. The manifest tells us who must finish; the receipt tells us which operation that terminal result belongs to.

Keep invocation order separate from completion order

N04 releases beta before alpha. EventEmitter still invokes the registered listeners synchronously in registration order, alpha then beta, as documented for v22.14.0. But completion order is now beta then alpha because the gates intentionally reverse it.

The ledger should therefore preserve both facts rather than collapse them into one array index story. Invocation order can be alpha, beta; receipt and completion order can be beta, alpha. The operation reconciler associates terminal results by handler identity, not by “first result means first listener.” This is also why I do not infer completion from registration position or from Promise.allSettled() input order. Input order is useful for stable association when the application already controls the array; it is not evidence about which operation physically completed first.

N04 becomes complete only after both completion acknowledgements and both exact receipts exist. Until then the resource remains open. Reversed completion is normal asynchronous behavior, not an error condition.

Test captureRejections without treating it as a join

N05 enables captureRejections but keeps the all-success gates closed. The expected checkpoint is intentionally boring: both listeners have entered, neither has completed, and the error ledger is empty. That empty error ledger does not prove completion. It proves only that the synchronous observer has not been given a captured rejection by that point. Node.js documents captureRejections as automatic handling for promise rejections from listeners; it is an error-routing mechanism, not a listener-join result.

N06 then makes alpha reject after its gate opens while beta stays held. The rejection carries handlerId: 'alpha', allowing the fixture's rejection hook to record the expected identity and message. The hook is synchronous and nonthrowing by fixture policy; it records evidence and resolves a separate observer acknowledgement. Only after that acknowledgement does the test assert that beta remains unfinished. The test then releases beta and drains both original listener promises under test ownership.

Node.js's archived Errors documentation distinguishes several asynchronous error channels, including rejected promises, callback-reported errors, and errors emitted by EventEmitter instances. That is why I retain the channel and handler identity in the ledger instead of translating every problem into one generic “failed” bit. An error report says something failed on a particular path. It does not establish that beta finished, that beta was cancelled, or that beta's future resource access disappeared.

The N06 operational checkpoint is therefore still HOLD_INFLIGHT while beta is gated. Once beta is drained, the business operation is failed, but the error route itself never served as a completion join. Capturing rejections helps own a rejection channel; it does not redefine what emit() returns.

Give business handlers an explicit returned-work contract

The repair is a separate application API for work whose completion matters. I use a frozen required manifest and a registry of { id, run } records. The registry validates configuration first, calls each business handler exactly once, requires a native promise from each call, retains those original promises, waits for all of them to settle, validates fulfilled receipts, and only then lets the resource owner close.

The key contract belongs to the handler, not to Promise.allSettled(): the promise returned by a handler must remain pending until all resource access owned by that handler is finished. If alpha starts a child operation that will later touch the resource, alpha must await or return work that includes that child before issuing its successful receipt. The registry can join only promises it actually owns. It cannot discover arbitrary background work by introspection.

This is a new application interface, so its callers need review. A caller that previously treated the event as fire-and-forget may keep using notification semantics if no downstream release depends on handler completion. A caller that owns the shared resource must use the owned-work interface and interpret its decision. Merely renaming the event to workComplete, making the listener async, or writing await emitter.emit(...) does not change the underlying Node.js return contract.

I also keep notification and owned execution separate conceptually. The same business behavior may be exposed through a notification adapter in one path and through the registry in another, but the resource-owning path must have a direct completion contract. This avoids pretending that every event in an application suddenly needs request/response semantics.

The returned-work rule is therefore part of the public application contract even though the implementation uses ordinary promises. A handler that previously started work and intentionally detached it may be perfectly acceptable on a pure notification path; the same implementation is invalid on the owned path if that child can still touch the shared resource. Reviewers should treat that distinction as a compatibility question. Moving a handler into the registry without checking its child-work behavior can create a false completion boundary while leaving the source code looking unchanged.

The receipt ledger is not a substitute for the promise boundary either. A handler should issue its successful receipt only after its owned resource work is complete. Recording a receipt early and then continuing work would merely move the omission from the return statement into the receipt semantics. In other words, terminal evidence must describe terminal work. The registry's job is to preserve and reconcile that evidence; it is not to reinterpret an optimistic status marker as proof that later accesses cannot occur.

conotcallevent

Do not call EventEmitter listeners a second time

A tempting adapter is emitter.listeners('work'), followed by manually invoking each function and joining what it returns. I do not use that approach. It turns introspection into execution and risks running business work twice when normal emit() also occurred. It can also change wrapper semantics, once behavior, invocation context, and whatever policy the emitter owner attached around listener dispatch.

The small registry avoids that category of bug because it owns the business handlers directly. The EventEmitter wrapper, when needed, calls a business handler once for notification use. The owned registry calls a business handler once for an explicitly owned operation. It does not enumerate listeners() or rawListeners() and replay the functions that EventEmitter already owns. Completion responsibility is explicit at the application boundary rather than reverse-engineered from emitter internals.

Close only after every required handler settles

N07 is the positive repair case. The registry validates exactly two entries, starts alpha and beta once, and captures their returned native promises. Both handlers enter and wait. The test releases alpha, awaits alpha's completion acknowledgement, and checks that the registry result is still pending and the resource is still open. That alpha-only checkpoint is the decisive proof that the registry has not confused one success with operation completion.

After beta is released, both returned promises settle. For the finite array of ordinary native promises admitted by this fixture, Promise.allSettled() returns only after each input has produced either a fulfilled or rejected outcome, and the result records each status with its value or reason. That behavior is specified by ECMAScript 2025 (ECMA-262, 16th edition). The application inference is deliberately narrower: the aggregate can wait for the promises we supplied; it cannot discover child work omitted from those promises.

N07 then validates the two exact receipts by identity and operation ID. Only after that reconciliation does close() run. The ledger must show the close sequence number greater than every accepted resource-access sequence number, and closeCount must equal one. The expected decision is COMPLETE.

“All settled” is not the same as “all successful.” allSettled() is useful here because the resource owner needs terminal knowledge for every owned handler even when one fails. Business acceptance is a separate layer applied after settlement. That separation becomes N08.

Find the work a handler failed to return

N09 is the negative control that prevents a superficial “just use Promise.allSettled()” repair. Defective alpha starts a real child promise immediately. The child waits on its own gate and will later call resource.access('alpha', 'op-001'). Alpha then returns an already fulfilled, plausible receipt without awaiting or returning that child. Beta behaves correctly.

From the registry's limited view, both returned promises can fulfill. A naive join therefore finishes and closes the resource. Only the test harness's independent ownership of the detached child reveals that alpha still has resource-owning work outside its returned promise. After close, the harness opens the child gate. The child's access attempt is recorded with open: false and rejects because the resource has already been closed. That is the expected laboratory witness for REPAIR_RETURN_CONTRACT.

This is not a failure of Promise.allSettled(). Under its specified contract it tracks the inputs supplied to it and records their terminal states. The defect is upstream: alpha's returned-work contract omitted a started child that still owned resource access. No aggregate combinator can infer an invisible descendant merely because it was created inside the handler.

The neighboring Refonte Learning article on how to audit rejection evidence after Promise.any addresses a different evidence problem: retaining rejection information around winner selection. N09 has no winner selection and does not need an AggregateError matrix. Its novelty is source ownership: a successful-looking returned promise can still be incomplete.

A fulfilled promise can still omit an owned child

The defective boundary is conceptually this:

async function defectiveAlpha() {
  const child = doResourceWorkLater();

  testOnlyDetachedInventory.push(child);

  return {
    operationId: OPERATION_ID,
    handlerId: 'alpha',
    status: 'ok',
  };
}

The corrected boundary is:

async function repairedAlpha() {
  await doResourceWorkLater();

  return {
    operationId: OPERATION_ID,
    handlerId: 'alpha',
    status: 'ok',
  };
}

The repaired variant must run with fresh state. It does not reuse the already-closed resource or erase the original late-access evidence. In the defective run, the harness still drains the detached child and retains its rejected settlement. In the repaired run, alpha's returned promise stays pending until the child has completed its resource access, so the registry cannot reach its close decision early.

The reviewer should therefore ask two questions at every handler boundary: “What resource-owning child work can this handler start?” and “Is all of that work represented in the promise the registry owns?” A fulfilled promise answers only the second question if the implementation contract is trustworthy. It does not prove that no unreturned child exists.

Validate the required handler manifest

N10 makes configuration completeness an admission check rather than a postmortem. The registry's expected IDs are exactly alpha and beta. Before invoking either function, it checks that there are exactly two entries, that the sorted ID set matches the required manifest, that no ID is duplicated, and that each run field is callable. Missing beta and duplicate alpha are rejected before any handler starts.

This matters because an aggregate over the wrong set can be perfectly terminal and still prove the wrong operation. Promise.allSettled([]) can settle without waiting for business work; a one-element array can faithfully represent only alpha; a duplicate array can run alpha twice if validation comes after invocation. None of those outcomes establishes the required two-handler operation. The article-defined decision is BLOCK_CONFIGURATION.

The operation ID is also immutable. The registry does not accept a receipt for another operation and does not rewrite a mismatched result to make it fit. The permitted receipt keys are operationId, handlerId, and status; the strict fixture comparison rejects missing, extra, or mismatched fields. No unexpected handler receipt is accepted as a substitute for a required one.

I avoid “helpful” deduplication after work has begun. If configuration says alpha twice, that is a configuration error, not permission to pick one execution and ignore the other. The safe boundary is before invocation, when no resource access has started. Once a business handler has run, reverting the array in caller memory does not undo that execution.

Node's strict assertion module is appropriate for these evidence checks: assert.strictEqual and assert.deepStrictEqual compare the exact scalar and record shapes used by the fixture, while assert.rejects() awaits the asynchronous rejection contract when used correctly. These APIs are checker mechanisms. Their documentation is not evidence that this unexecuted fixture has passed.

Preserve failures and drain owned work

N08 keeps the failure path deliberately narrow. Alpha rejects after its gate opens; beta remains pending. The registry does not close on alpha's failure because beta still owns possible future access. It waits until beta settles too. Only then may the resource owner close, and the business decision remains FAILED_AFTER_DRAIN rather than being rewritten as success merely because cleanup completed.

That yields three separate states that should stay separate in code review. Resource lifetime asks whether any owned work can still access the resource. Business result asks whether every required handler fulfilled with a valid receipt. Test cleanup asks whether the harness has drained the promises it created so the next case starts cleanly. A successful drain can coexist with a failed business operation.

For a broader sibling-lifecycle problem after aggregate failure, Refonte Learning's Python playbook on task ownership after an asyncio aggregate fails explores a different runtime and cancellation policy. I do not translate that cancellation matrix into JavaScript here. N08's rule is simply to retain the resource until all owned returned work is terminal.

HOLD_INFLIGHT covers the cases where that terminal ownership is not yet known: a required promise is still pending, a watchdog expires, or evidence cannot establish whether resource-owning work remains. Rolling back a caller to older code does not stop work that has already started, undo recorded accesses, or make an unresolved promise terminal. Recovery therefore begins by preserving the resource and evidence until ownership is clear; it does not assume automatic replay, cancellation, or compensation.

Reconcile the resource and receipt ledgers

The case matrix below is a compact operational map. Because the article did not execute the fixture, every observation remains EXPECTED / NOT EXECUTED. “Returned work” means what the caller or registry actually owns, not arbitrary work the source code may have started invisibly.

Case

Expected checkpoint

Returned work visible to owner

Resource state at checkpoint

Article decision

Observation

N01

Both entered; both gates closed; emit() is true; no failures

EventEmitter returns no promise inventory

Open; both still need it

HOLD_INFLIGHT

EXPECTED / NOT EXECUTED

N02

await emit() returns; both completions still absent

Still only the Boolean from emit()

Open

HOLD_INFLIGHT

EXPECTED / NOT EXECUTED

N03

Alpha receipt terminal; beta held

Harness privately retains both listener promises

Open; beta still owns access

HOLD_INFLIGHT

EXPECTED / NOT EXECUTED

N04

Invocation alpha/beta; completion beta/alpha

Harness retains promises by ID

Open until both drain

COMPLETE only after both

EXPECTED / NOT EXECUTED

N05

captureRejections enabled; no errors; both held

No join result from captureRejections

Open

HOLD_INFLIGHT

EXPECTED / NOT EXECUTED

N06

Alpha rejection routed; beta still held

Original alpha rejection plus pending beta retained by test

Open until beta drains

HOLD_INFLIGHT, then failed

EXPECTED / NOT EXECUTED

N07

Owned registry; alpha done, beta pending; then beta done

Both required native promises

Open through alpha-only checkpoint; one close after both

COMPLETE

EXPECTED / NOT EXECUTED

N08

One rejection, one pending, then both terminal

Both required native promises

Open until both settle; then close

FAILED_AFTER_DRAIN

EXPECTED / NOT EXECUTED

N09

Returned alpha receipt hides gated child

Registry misses child; test tracks it independently

Naive close occurs before child's attempted access

REPAIR_RETURN_CONTRACT

EXPECTED / NOT EXECUTED

N10

Missing or duplicate required ID

No business work admitted

Remains untouched

BLOCK_CONFIGURATION

EXPECTED / NOT EXECUTED


A useful evidence bundle retains more than a terminal label. At minimum I want the frozen manifest, operation ID, invocation/entry ledger, resource-access attempts with open/closed state, terminal completion markers, per-handler receipts, rejection records with channel and identity, aggregate settlements for owned promises, and the close record. That lets a reviewer reconstruct why the resource was or was not released.

The sequence numbers are especially valuable because they test the release boundary directly. A close record after the final accepted access is consistent with the contract. A close record before an accepted access, or an attempted access with open: false, is evidence of a lifetime violation even if every visible promise later settles.

Reject incomplete and reordered evidence

The checker should reject a copied bundle that omits beta's completion even if alpha's receipt and the close record look correct. It should also reject a bundle in which close's sequence number is less than or equal to the final accepted resource access. Those are deliberate evidence mutations: one removes required terminal identity; the other reorders the lifetime boundary.

The fixture uses node:assert/strict for exact comparisons and awaited rejection assertions. The archived v22.14.0 Assert documentation states that assert.rejects() waits for the supplied promise or returned promise and then checks rejection, while strict/deep-strict assertion APIs provide exact checking tools for the values under test. That documents the mechanics of the checker, not a successful run.

Diagnostic success must also be separated from operation acceptance. N09 can behave exactly as designed (registry appears complete, resource closes, detached child later hits the closed resource), and the test can therefore be successful because it exposed the contract breach. The operation is still unacceptable and maps to REPAIR_RETURN_CONTRACT. Likewise, N10 can successfully demonstrate that configuration is blocked without producing a business receipt.

Choose accept, repair or hold for the interface

The final decision should be owned explicitly rather than inferred from whichever log line appears last.

Decision

When I use it

Primary owner action

COMPLETE

Every required returned promise settled fulfilled, every exact receipt matches, ledger order is valid, close occurs once after final owned access

Resource owner may accept the close

FAILED_AFTER_DRAIN

All owned returned work is terminal, at least one required handler rejected, and the resource can now be released safely

Preserve failure evidence; do not relabel business success

REPAIR_RETURN_CONTRACT

A handler returned terminal success while separately observed owned child work remained active, or receipt semantics do not cover required work

Handler owner expands the returned promise boundary and reruns with fresh state

BLOCK_CONFIGURATION

Required IDs are missing, duplicated, unexpected, or otherwise invalid before invocation

Operation owner fixes the manifest before starting work

HOLD_INFLIGHT

Required work is still pending or ownership cannot yet be established

Resource owner keeps the resource open and preserves evidence

The ownership split is intentional. The handler owner defines what the returned promise covers and must include every child operation that can still use the resource. The operation owner declares required participants and the immutable operation identity. The resource owner authorizes close only from reconciled terminal evidence. The reviewer checks that the fixture, manifest, receipts, settlements, and sequence ledger support the stated decision.

Safe recovery from incomplete work begins with HOLD_INFLIGHT: keep the resource available while known owned work is still active, preserve the promise and ledger evidence, and avoid starting duplicate work merely to make the state look cleaner. If the returned-work boundary itself is incomplete, move to REPAIR_RETURN_CONTRACT; do not paper over the gap with a longer timeout or by awaiting the emit() Boolean.

There is also a future-code rollback boundary. Reverting a commit can prevent new operations from entering a defective interface, but it cannot retroactively cancel promises that earlier code already started or undo resource accesses already recorded. The existing in-flight operation still needs its own ownership decision. This article does not prescribe retries, compensation, or automatic replay; those policies depend on application semantics outside the fixture.

The interface choice is therefore straightforward. Keep EventEmitter where the intent is notification and callers do not require listener completion to release shared state. Introduce the small owned registry where completion is part of the business contract. captureRejections may remain useful for error routing, but it is not the completion boundary. Promise.allSettled() may join a finite set of owned promises, but only after the handler contract makes that set complete.

Develop stronger backend API contracts with Refonte Learning

This fixture exercises backend skills that are broader than EventEmitter: defining API ownership, making asynchronous completion explicit, testing resource lifetime, preserving failure channels, and reviewing evidence instead of relying on timing. Refonte Learning's Backend Developer Program lists Node.js and Express, MongoDB and SQL, RESTful APIs and microservices, authentication and authorization, testing and debugging, Docker/cloud deployment, and a capstone among its competencies. The page lists a three-month period and 10–12 hours per week, and it describes practical projects, seasoned guidance, and potential internship opportunities.

The same page says applicants need basic programming understanding and, in its admissions block, must be working toward a bachelor's or higher-level degree. It also states that successful completion carries a Training Certificate and a Certificate of Internship. Those are program-page claims, not employment guarantees. Exact Node.js versions taught, specialized EventEmitter or captureRejections completion coverage, individual mentoring cadence, and internship allocation or schedule are not verified here.

For wider context, Refonte Learning also discusses Node.js and other backend framework choices. If you are strengthening backend fundamentals, API design, and testing discipline, the Backend Developer Program is the appropriate place to review the verified curriculum and current admissions details rather than assuming this exact laboratory is part of the syllabus.