denosaurs / event

📆 Strictly typed event emitter with asynciterator support
https://deno.land/x/event
MIT License
42 stars 5 forks source link

Add in emitter.waitFor #2

Closed Cormanz closed 2 years ago

Cormanz commented 2 years ago

Hi! I'm making a pull request to add a backwards compatible change, adding in the method EventEmitter.waitFor. This method is useful, since it allows for asynchronously waiting for a single event dynamically.

const emitter = new EventEmitter<{
    number: [ number ]
}>();

setTimeout(() => {
    emitter.emit('number', 5489);
}, 1000);

const [ num ] = await emitter.waitFor('number');
console.log('Number:', num);

Attached is an example of usage of this method.

crowlKats commented 2 years ago

This is already possible, see se overload at https://github.com/denosaurs/event/blob/master/mod.ts#L81. so your code would be:

const emitter = new EventEmitter<{
    number: [ number ]
}>();

setTimeout(() => {
    emitter.emit('number', 5489);
}, 1000);

const [ num ] = await emitter.once('number');
console.log('Number:', num);