Skip to content
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

feat(breaking): return errors instead of throwing #120

Closed
wants to merge 9 commits into from
Closed
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
24 changes: 17 additions & 7 deletions index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -190,6 +190,11 @@ emitter.emit('open', 1);
emitter.emit('other');
```
*/

export type EmitErrorResult = [unknown, ...unknown[]];
export type EmitSuccessResult = undefined;
export type EmitResult = EmitErrorResult | EmitSuccessResult;

export default class Emittery<
EventData = Record<EventName, any>, // TODO: Use `unknown` instead of `any`.
AllEventData = EventData & OmnipresentEventData,
Expand Down Expand Up @@ -490,26 +495,31 @@ export default class Emittery<
/**
Trigger an event asynchronously, optionally with some data. Listeners are called in the order they were added, but executed concurrently.

@returns A promise that resolves when all the event listeners are done. *Done* meaning executed if synchronous or resolved when an async/promise-returning function. You usually wouldn't want to wait for this, but you could for example catch possible errors. If any of the listeners throw/reject, the returned promise will be rejected with the error, but the other listeners will not be affected.
@returns A promise that resolves when all event listeners are done:
- If all listeners succeed, resolves with undefined
- If any listeners fail, resolves with an array of their errors
All listeners will execute regardless of whether other listeners throw/reject.
*/
emit<Name extends DatalessEvents>(eventName: Name): Promise<void>;
emit<Name extends DatalessEvents>(eventName: Name): Promise<EmitResult>;
emit<Name extends keyof EventData>(
eventName: Name,
eventData: EventData[Name]
): Promise<void>;
): Promise<EmitResult>;

/**
Same as `emit()`, but it waits for each listener to resolve before triggering the next one. This can be useful if your events depend on each other. Although ideally they should not. Prefer `emit()` whenever possible.

If any of the listeners throw/reject, the returned promise will be rejected with the error and the remaining listeners will *not* be called.
If any of the listeners throw/reject, the remaining listeners will *not* be called.

@returns A promise that resolves when all the event listeners are done.
@returns A promise that resolves when all event listeners are done:
- If all listeners succeed, resolves with undefined
- If any listeners fail, resolves with an array with exactly one error
*/
emitSerial<Name extends DatalessEvents>(eventName: Name): Promise<void>;
emitSerial<Name extends DatalessEvents>(eventName: Name): Promise<undefined | [unknown]>;
emitSerial<Name extends keyof EventData>(
eventName: Name,
eventData: EventData[Name]
): Promise<void>;
): Promise<undefined | [unknown]>;

/**
Subscribe to be notified about any event.
Expand Down
36 changes: 32 additions & 4 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -361,18 +361,35 @@ export default class Emittery {
const staticAnyListeners = isMetaEvent(eventName) ? [] : [...anyListeners];

await resolvedPromise;

const errors = [];

async function runListener(listener, ...args) {
try {
await listener(...args);
} catch (error) {
errors.push(error);
}
}

await Promise.all([
...staticListeners.map(async listener => {
if (listeners.has(listener)) {
return listener(eventData);
await runListener(listener, eventData);
}
}),
...staticAnyListeners.map(async listener => {
if (anyListeners.has(listener)) {
return listener(eventName, eventData);
await runListener(listener, eventName, eventData);
}
}),
]);

if (errors.length > 0) {
return errors;
}

return undefined;
}

async emitSerial(eventName, eventData) {
Expand All @@ -390,19 +407,30 @@ export default class Emittery {
const staticAnyListeners = [...anyListeners];

await resolvedPromise;

/* eslint-disable no-await-in-loop */
for (const listener of staticListeners) {
if (listeners.has(listener)) {
await listener(eventData);
try {
await listener(eventData);
} catch (error) {
return [error];
}
}
}

for (const listener of staticAnyListeners) {
if (anyListeners.has(listener)) {
await listener(eventName, eventData);
try {
await listener(eventName, eventData);
} catch (error) {
return [error];
}
}
}
/* eslint-enable no-await-in-loop */

return undefined;
}

onAny(listener) {
Expand Down
7 changes: 3 additions & 4 deletions readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -388,16 +388,15 @@ iterator
```

#### emit(eventName, data?)

Trigger an event asynchronously, optionally with some data. Listeners are called in the order they were added, but executed concurrently.

Returns a promise that resolves when all the event listeners are done. *Done* meaning executed if synchronous or resolved when an async/promise-returning function. You usually wouldn't want to wait for this, but you could for example catch possible errors. If any of the listeners throw/reject, the returned promise will be rejected with the error, but the other listeners will not be affected.
Returns a promise that resolves when all the event listeners are done. *Done* meaning executed if synchronous or resolved when an async/promise-returning function. You usually wouldn't want to wait for this, but you could for example catch possible errors. If any of the listeners throw/reject, the returned promise will resolve with an array containing all the errors. All listeners will execute regardless of whether other listeners throw/reject.

#### emitSerial(eventName, data?)

Same as above, but it waits for each listener to resolve before triggering the next one. This can be useful if your events depend on each other. Although ideally they should not. Prefer `emit()` whenever possible.
Trigger an event asynchronously, optionally with some data. Listeners are called in the order they were added and executed serially.

If any of the listeners throw/reject, the returned promise will be rejected with the error and the remaining listeners will *not* be called.
Returns a promise that resolves when all the event listeners are done. *Done* meaning executed if synchronous or resolved when an async/promise-returning function. If any of the listeners throw/reject, the returned promise will resolve with an array containing exactly one error and remaining listeners will not be called. If all listeners succeed, the promise resolves with `undefined`.

#### onAny(listener)

Expand Down
71 changes: 57 additions & 14 deletions test/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -588,20 +588,6 @@ test('emit() - returns undefined', async t => {
t.is(await emitter.emit('🦄🦄'), undefined);
});

test('emit() - throws an error if any listener throws', async t => {
const emitter = new Emittery();

emitter.on('🦄', () => {
throw new Error('🌈');
});
await t.throwsAsync(emitter.emit('🦄'), {instanceOf: Error});

emitter.on('🦄🦄', async () => {
throw new Error('🌈');
});
await t.throwsAsync(emitter.emit('🦄🦄'), {instanceOf: Error});
});

test('emitSerial()', async t => {
const emitter = new Emittery();
const promise = pEvent(emitter, '🦄');
Expand Down Expand Up @@ -1333,3 +1319,60 @@ test('debug mode - handles circular references in event data', async t => {

await t.notThrowsAsync(emitter.emit('test', data));
});

test('emit() - returns undefined when all listeners succeed', async t => {
const emitter = new Emittery();

emitter.on('test', () => {});
emitter.on('test', async () => {});

const result = await emitter.emit('test', 'data');
t.is(result, undefined);
});

test('emit() - returns array of errors when listeners fail', async t => {
const emitter = new Emittery();
const syncError = new Error('sync error');
const asyncError = new Error('async error');

emitter.on('test', () => {
throw syncError;
});
emitter.on('test', async () => {
throw asyncError;
});

const result = await emitter.emit('test', 'data');
t.true(Array.isArray(result));
t.is(result.length, 2);
t.is(result[0], syncError);
t.is(result[1], asyncError);
});

test('emitSerial() - returns undefined when all listeners succeed', async t => {
const emitter = new Emittery();

emitter.on('test', () => {});
emitter.on('test', async () => {});

const result = await emitter.emitSerial('test', 'data');
t.is(result, undefined);
});

test('emitSerial() - returns array of the error when listeners fail', async t => {
const emitter = new Emittery();
const syncError = new Error('sync error');
const asyncError = new Error('async error');

emitter.on('test', () => {
throw syncError;
});
emitter.on('test', async () => {
throw asyncError;
});

const result = await emitter.emitSerial('test', 'data');
t.true(Array.isArray(result));
t.is(result.length, 1);
t.is(result[0], syncError);
});