Skip to content

Conversation

zone117x
Copy link
Contributor

@zone117x zone117x commented May 26, 2025

Implement onceWhen helper function.

Description

Creates a Promise that resolves when the specified eventName is emitted by the EventEmitter and the provided predicate returns true for the emitted arguments.

Similar to events.once, but includes support for a predicate function to filter events. Only events for which the predicate returns true will cause the Promise to resolve. The resolved value is an array of the arguments emitted with the event. Supports typed EventEmitters and optional cancellation via AbortSignal.

Examples

Example 1

import { EventEmitter } from 'node:events';

const emitter = new EventEmitter<{
  myEvent: [id: number, msg: string];
}>();

setTimeout(() => {
  for (let i = 0; i <= 5; i++) {
    emitter.emit('myEvent', i, `Message ${i}`);
  }
}, 100);

const [id, msg] = await onceWhen(emitter, 'myEvent', (id, msg) => id === 3);

// outputs: "Received event with id: 3, message: Message 3"
console.log(`Received event with id: ${id}, message: ${msg}`);

Example 2

import { EventEmitter } from 'node:events';

const emitter = new EventEmitter<{ myEvent: [id: number, msg: string] }>();

const signal = AbortSignal.timeout(10);

setTimeout(() => emitter.emit('myEvent', 1, 'Hello'), 1000);

const whenPromise = onceWhen(emitter, 'myEvent', id => id === 1, { signal });

// This rejects because the signal is aborted before the event is emitted
await expect(whenPromise).rejects.toThrow(signal.reason);

Copy link
Collaborator

@rafaelcr rafaelcr left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Awesome

@zone117x zone117x merged commit 840b2f1 into develop Jun 2, 2025
3 checks passed
@zone117x zone117x deleted the feaet/once-when branch June 2, 2025 09:12
zone117x added a commit that referenced this pull request Jun 2, 2025
* feat: implement `onceWhen` helper function

* chore: add example usage docs

* chore: add example usage docs
hirosystems-release-bot bot added a commit that referenced this pull request Jun 2, 2025
## [1.9.0](v1.8.0...v1.9.0) (2025-06-02)

### Features

* onceWhen function ([#43](#43)) ([840b2f1](840b2f1))
* onceWhen function ([#43](#43)) ([#44](#44)) ([4013b38](4013b38))
* worker thread pool ([#41](#41)) ([16c9616](16c9616))

### Bug Fixes

* git info check should not throw when debugging ([#39](#39)) ([66f44d5](66f44d5))
@hirosystems-release-bot
Copy link

🎉 This PR is included in version 1.9.0 🎉

The release is available on:

Your semantic-release bot 📦🚀

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

Successfully merging this pull request may close these issues.

2 participants