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

Implement events.on #76

Open
goto-bus-stop opened this issue Aug 6, 2020 · 2 comments
Open

Implement events.on #76

goto-bus-stop opened this issue Aug 6, 2020 · 2 comments

Comments

@goto-bus-stop
Copy link
Member

https://nodejs.org/api/events.html#events_events_on_emitter_eventname

Introduced in Node.js 13.6.0, require('events').on creates an Async Iterator over all the emits of an event.

@abhishiv
Copy link

I am trying to code a fromEventEmitter function however it only iterates over one element even when two events are fired in succession.


export function fromEventEmitter<EventDef extends Array<unknown> = unknown[]>(
  emitter: EventEmitter,
  eventName: string,
  config: { closeEventName: string } = { closeEventName: "close" }
) {
  return (async function* (): AsyncIterable<EventDef> {
    let isOpen = true;
    emitter.once(config.closeEventName, () => (isOpen = false));
    while (isOpen) {
      console.log("cc", isOpen);
      yield await new Promise((resolve) => {
        const handler = (...args: any[]) => {
          // pauseable.pause(emitter);
          resolve((args as unknown) as EventDef);
          setTimeout(() => {}, 0);
        };
        emitter.on(eventName, handler);
        // pauseable.resume(emitter);
      });
    }
  })();
    peer.port.emit("incoming", {
      id: "1",
      path: ["viewport2", "viewport1"],
      message: {
        type: IMessageType.REQUEST,
        payload: {},
      },
    } as IRoutePacket<unknown>);
    peer.port.emit("incoming", {
      id: "2",
      path: ["viewport2", "viewport1"],
      message: {
        type: IMessageType.REQUEST,
        payload: {},
      },
    } as IRoutePacket<unknown>);

I'm just trying to convert a EventEmitter into AsyncIterator

@tbwiss
Copy link

tbwiss commented Dec 22, 2022

Hi!
Is there an update that can be shared regarding this? I would also like to see this implemented. Even workarounds are appreciated.
Thank you!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants