tome icon indicating copy to clipboard operation
tome copied to clipboard

Use a subscriber model to cleanup event promisification

Open anonhostpi opened this issue 1 month ago • 0 comments

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

anonhostpi avatar Oct 29 '25 22:10 anonhostpi