Skip to content

EventEmitter.on exits function after async iteration of events #32360

Closed
@mitsos1os

Description

@mitsos1os
  • Version:v.12.16.1
  • Platform: Linux 5.3.0-42-generic fix LICENSE #34~18.04.1-Ubuntu SMP Fri Feb 28 13:42:26 UTC 2020 x86_64 x86_64 x86_64 GNU/Linux
  • Subsystem:

What steps will reproduce the bug?

I am not sure if this is actually an issue or it works as expected, but the newly introduced EventEmiter.on functionality used in a for await, exits the function in which is called after iteration, without running the following commands. Notice the snippet from the actual documentation with an extra log line added:

const { on, EventEmitter } = require('events');

(async () => {
  const ee = new EventEmitter();

  // Emit later on
  process.nextTick(() => {
    ee.emit('foo', 'bar');
    ee.emit('foo', 42);
  });

  for await (const event of on(ee, 'foo')) {
    // The execution of this inner block is synchronous and it
    // processes one event at a time (even with await). Do not use
    // if concurrent execution is required.
    console.log(event); // prints ['bar'] [42]
  }
  console.log('The End'); // This is never printed...!
})();

However this is not the case using a regular AsyncIterator:

(async () => {
  
  async function* asyncGenerator() {
    let i = 0;
    while (i < 3) {
      yield i++;
    }
  }

  for await (const event of asyncGenerator()) {
    // The execution of this inner block is synchronous and it
    // processes one event at a time (even with await). Do not use
    // if concurrent execution is required.
    console.log(event); // prints ['bar'] [42]
  }
  console.log('The End'); // This is printed normally!
})();

So that is why I believe it is a problem with EventEmitter.on functionality...

What is the expected behavior?

I believe it should continue execution of code after the loop

What do you see instead?

Code following loop is not run.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions