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

Fix handling of synchronous exceptions thrown from executor function #41

Merged
merged 1 commit into from
Sep 18, 2023
Merged
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
13 changes: 6 additions & 7 deletions spec/index.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -149,14 +149,13 @@ it('*synchronous* exception thrown from executor function propagates up only to
const it1 = iterable[Symbol.asyncIterator]();
const it2 = iterable[Symbol.asyncIterator]();

const it1IterationPromise = it1.next();
const it2IterationPromise = it2.next();
const it1NextPromise = it1.next();
const it2NextPromise = it2.next();

expect(await getPromiseState(it1IterationPromise)).toBe('REJECTED');
expect(await getPromiseState(it2IterationPromise)).toBe('PENDING');
await expect(it1IterationPromise).rejects.toMatchObject({
message: 'oops...',
});
expect(await getPromiseState(it1NextPromise)).toBe('REJECTED');
expect(await getPromiseState(it2NextPromise)).toBe('RESOLVED');
await expect(it1NextPromise).rejects.toMatchObject({ message: 'oops...' });
await expect(it2NextPromise).resolves.toMatchObject({ done: true, value: undefined });
});

it('*asynchronous* exception thrown from executor function propagates up to multiple simultaneous consuming iterators', async () => {
Expand Down
14 changes: 9 additions & 5 deletions src/iterified.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,12 @@ function iterified<TNext>(executorFn: ExecutorFn<TNext>): IterifiedIterable<TNex

const gen = (async function* () {
if (++activeIteratorCount === 1) {
possiblyReturnedCleanupFnPromise = executorFn(pushCb, doneCb, errorCb);
try {
possiblyReturnedCleanupFnPromise = executorFn(pushCb, doneCb, errorCb);
} catch (err) {
channel.close();
throw err;
}
if (possiblyReturnedCleanupFnPromise instanceof Promise) {
possiblyReturnedCleanupFnPromise.catch(err => closeIterable(true, err));
}
Expand All @@ -43,14 +48,13 @@ function iterified<TNext>(executorFn: ExecutorFn<TNext>): IterifiedIterable<TNex
}
})();

const originalGenReturn = gen.return as unknown as () => Promise<
IteratorReturnResult<undefined | void>
>;
const originalGenReturn = gen.return;

return Object.assign(gen, {
async return() {
await channelIterator.return();
return await originalGenReturn.call(gen);
await originalGenReturn.call(gen);
return { done: true as const, value: undefined };
},
});
},
Expand Down
Loading