Skip to content

Use a subscriber model to cleanup event promisification #17

Description

@anonhostpi

Your getKey workflow is clever, but can be challenging to follow.

I didn't want to add this proposal to my currently open PR, because its a different change, but I did want to drop it off with you: I recommend swapping the getKey logic out with a subscriber workflow that looks more like this:

import { on } from 'node:events';
import { EventEmitter } from 'node:events';

const emitter = new EventEmitter();

async function subscriber() {
  for await (const [data] of on(emitter, 'data')) {
    console.log('Got:', data);
  }
  console.log('Stream ended');
}

subscriber();

emitter.emit('data', 'A');
emitter.emit('data', 'B');
emitter.emit('end');

Node's event.on automatically converts events to promises by effectively wrapping events internally like this:

async function nextValue() {
  return new Promise(resolve => emitter.once("data", resolve));
}

Since it does this internally, it will likely offer a performance gain too.

Of course you'd have to bake your keymapping snippet into this, but I don't think that would be too challenging

Activity

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions