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(async): abortableAsyncIterable() should call .return() on the generator once aborted #5560

Merged
merged 4 commits into from
Aug 1, 2024
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
25 changes: 15 additions & 10 deletions async/abortable.ts
Original file line number Diff line number Diff line change
Expand Up @@ -144,16 +144,21 @@ async function* abortableAsyncIterable<T>(
signal.addEventListener("abort", abort, { once: true });

const it = p[Symbol.asyncIterator]();
while (true) {
const race = Promise.race([promise, it.next()]);
race.catch(() => {
signal.removeEventListener("abort", abort);
});
const { done, value } = await race;
if (done) {
signal.removeEventListener("abort", abort);
return;
try {
while (true) {
const race = Promise.race([promise, it.next()]);
race.catch(() => {
signal.removeEventListener("abort", abort);
});
const { done, value } = await race;
if (done) {
signal.removeEventListener("abort", abort);
return;
}
yield value;
}
yield value;
} catch (e) {
await it.return?.();
throw e;
}
}
31 changes: 31 additions & 0 deletions async/abortable_test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -130,3 +130,34 @@ Deno.test("abortable.AsyncIterable() handles already aborted signal", async () =
assertEquals(items, []);
clearTimeout(t);
});

Deno.test("abortable.AsyncIterable() calls return before throwing", async () => {
const c = new AbortController();
let returnCalled = false;
const iterable: AsyncIterable<string> = {
[Symbol.asyncIterator]: () => ({
next: () =>
new Promise((resolve) =>
setTimeout(() => resolve({ value: "Hello", done: false }), 1)
),
return: () => {
returnCalled = true;
return Promise.resolve({ value: undefined, done: true });
},
}),
};
setTimeout(() => c.abort(), 1);
const items: string[] = [];
const error = await assertRejects(
async () => {
for await (const item of abortable(iterable, c.signal)) {
items.push(item);
}
},
DOMException,
"The signal has been aborted",
);
assertEquals(returnCalled, true);
assertEquals(error.name, "AbortError");
assertEquals(items, []);
});