node icon indicating copy to clipboard operation
node copied to clipboard

doc: fix `events.once()` example with `AbortSignal`

Open foxxyz opened this issue 5 months ago • 0 comments

Upon trying out the example listed in the docs on how to use once() with an AbortSignal, I noticed that it does not work the way the example demonstrates.

When running the example below, calling ac.abort() prints Waiting for the event was canceled!, while the next line (ee.emit('foo')) seems to do nothing.

import { EventEmitter, once } from 'node:events';

const ee = new EventEmitter();
const ac = new AbortController();

async function foo(emitter, event, signal) {
  try {
    await once(emitter, event, { signal });
    console.log('event emitted!');
  } catch (error) {
    if (error.name === 'AbortError') {
      console.error('Waiting for the event was canceled!');
    } else {
      console.error('There was an error', error.message);
    }
  }
}

foo(ee, 'foo', ac.signal);
ac.abort(); // Abort waiting for the event
ee.emit('foo'); // Prints: Waiting for the event was canceled!

So I figured either the example is wrong, or the way this works has changed.

If it's the former, please consider this PR. If it's the latter, please let me know what I'm not understanding.

Thank you for a fantastic project 🙏🏽

foxxyz avatar Sep 27 '24 17:09 foxxyz