Skip to content

feat: reject emitted promise on error in EventEmitter #1596

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

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/lib/EventEmitter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ export class EventEmitter<EventTypes extends Record<string, (...args: any) => an
: EventParameters<EventTypes, Event>
> {
return new Promise((resolve, reject) => {
// TODO: handle errors
if (event !== 'error') this.once('error', reject as any);
this.once(event, resolve as any);
});
}
Expand Down
33 changes: 33 additions & 0 deletions tests/lib/eventEmitter.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import { EventEmitter } from 'openai/lib/EventEmitter';

interface TestEvents {
foo: (value: string) => void;
error: (err: Error) => void;
}

class TestEmitter extends EventEmitter<TestEvents> {

Check failure on line 8 in tests/lib/eventEmitter.test.ts

View workflow job for this annotation

GitHub Actions / lint

Type 'TestEvents' does not satisfy the constraint 'Record<string, (...args: any) => any>'.
emitFoo(value: string) {
this._emit('foo', value);
}
emitError(err: Error) {
this._emit('error', err);
}
}

describe('EventEmitter.emitted', () => {
test('resolves when event is emitted', async () => {
const emitter = new TestEmitter();
const promise = emitter.emitted('foo');
emitter.emitFoo('bar');
await expect(promise).resolves.toBe('bar');
});

test('rejects if error emitted before event', async () => {
const emitter = new TestEmitter();
const promise = emitter.emitted('foo');
const error = new Error('oops');
emitter.emitError(error);
emitter.emitFoo('bar');
await expect(promise).rejects.toBe(error);
});
});
Loading