Skip to content
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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
events: assume an EventEmitter if emitter.on is a function
Assume that the `emitter` argument of `EventEmitter.once()` is an
`EventEmitter` if `emitter.on` is a function.

Refs: 4b3654e923e7c3c2
Refs: websockets/ws#1795
  • Loading branch information
lpinca committed Oct 26, 2020
commit 32067a6324b85b2fa1f8b6af8ee23016f28f295c
5 changes: 4 additions & 1 deletion lib/events.js
Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change
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());