Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[v12.x] events: assume an EventEmitter if emitter.on is a function #35818

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
5 changes: 4 additions & 1 deletion lib/events.js
Expand Up @@ -623,7 +623,10 @@ function unwrapListeners(arr) {

function once(emitter, name) {
return new Promise((resolve, reject) => {
if (typeof emitter.addEventListener === 'function') {
if (
typeof emitter.addEventListener === 'function' &&
typeof emitter.on !== 'function'
) {
// EventTarget does not have `error` event semantics like Node
// EventEmitters, we do not listen to `error` events here.
emitter.addEventListener(
Expand Down
22 changes: 22 additions & 0 deletions test/parallel/test-events-once.js
Expand Up @@ -166,6 +166,27 @@ async function onceWithEventTargetError() {
strictEqual(Reflect.has(et.events, 'error'), false);
}

async function assumesEventEmitterIfOnIsAFunction() {
const ee = new EventEmitter();
ee.addEventListener = () => {};

const expected = new Error('kaboom');
let err;
process.nextTick(() => {
ee.emit('error', expected);
});

try {
await once(ee, 'myevent');
} catch (_e) {
err = _e;
}

strictEqual(err, expected);
strictEqual(ee.listenerCount('error'), 0);
strictEqual(ee.listenerCount('myevent'), 0);
}

Promise.all([
onceAnEvent(),
onceAnEventWithTwoArgs(),
Expand All @@ -175,4 +196,5 @@ Promise.all([
onceWithEventTarget(),
onceWithEventTargetTwoArgs(),
onceWithEventTargetError(),
assumesEventEmitterIfOnIsAFunction(),
]).then(common.mustCall());