Skip to content

Commit

Permalink
fix(async): abortable should not change original outputs (#5609)
Browse files Browse the repository at this point in the history
* fix(async): abortable should not change original outputs

* fix: according to code review

* revert

---------

Co-authored-by: Asher Gomez <[email protected]>
  • Loading branch information
raaymax and iuioiua authored Aug 5, 2024
1 parent 82e50a9 commit ed19729
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 1 deletion.
4 changes: 3 additions & 1 deletion async/abortable.ts
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,7 @@ export function abortable<T>(p: Promise<T>, signal: AbortSignal): Promise<T>;
* assertEquals(items, []);
* ```
*/

export function abortable<T>(
p: AsyncIterable<T>,
signal: AbortSignal,
Expand Down Expand Up @@ -153,7 +154,8 @@ async function* abortableAsyncIterable<T>(
const { done, value } = await race;
if (done) {
signal.removeEventListener("abort", abort);
return;
const result = await it.return?.(value);
return result?.value;
}
yield value;
}
Expand Down
40 changes: 40 additions & 0 deletions async/abortable_test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -166,3 +166,43 @@ Deno.test("abortable.AsyncIterable() calls return before throwing", async () =>
assertEquals(items, []);
clearTimeout(timeoutId!);
});

Deno.test("abortable.AsyncIterable() behaves just like original when not aborted", async () => {
async function* gen() {
yield 1;
yield await Promise.resolve(2);
yield 3;
return 4;
}
const normalIterator = gen();
const abortController = new AbortController();
const abortableIterator = abortable(gen(), abortController.signal);

assertEquals(await abortableIterator.next(), await normalIterator.next());
assertEquals(await abortableIterator.next(), await normalIterator.next());
assertEquals(await abortableIterator.next(), await normalIterator.next());
assertEquals(await abortableIterator.next(), await normalIterator.next());
assertEquals(await abortableIterator.next(), await normalIterator.next());
});

Deno.test("abortable.AsyncIterable() behaves just like original when return is called", async () => {
async function* gen() {
yield 1;
yield await Promise.resolve(2);
yield 3;
return 4;
}
const normalIterator = gen();
const abortController = new AbortController();
const abortableIterator = abortable(gen(), abortController.signal);

assertEquals(
await abortableIterator.next(123),
await normalIterator.next(123),
);
assertEquals(
await abortableIterator.return(321),
await normalIterator.return(321),
);
assertEquals(await abortableIterator.next(), await normalIterator.next());
});

0 comments on commit ed19729

Please sign in to comment.