Skip to content

Commit

Permalink
make ReadableIterator an async iterable iterator
Browse files Browse the repository at this point in the history
  • Loading branch information
jackyzha0 committed Oct 16, 2024
1 parent 258fe9f commit 687fc36
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 1 deletion.
19 changes: 19 additions & 0 deletions __tests__/streams.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -200,6 +200,25 @@ describe('Readable unit', () => {
expect(values).toEqual([1, 2].map(Ok));
});

it('should allow calling next and then turning it into an asyncIterator', async () => {
const readable = new ReadableImpl<number, SomeError>();
const iterator = readable[Symbol.asyncIterator]();
const next = iterator.next();
readable._pushValue(Ok(1));
readable._pushValue(Ok(2));
readable._pushValue(Ok(3));
readable._triggerClose();
expect(await next).toEqual({ value: Ok(1), done: false });

let i = 0;
for await (const value of iterator) {
expect(value).toEqual(Ok(i + 2));
i++;
}

expect(await iterator.next()).toEqual({ value: undefined, done: true });
});

it('should support for-await-of with break', async () => {
const readable = new ReadableImpl<number, SomeError>();

Expand Down
6 changes: 5 additions & 1 deletion router/streams.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ export type ReadableResult<T, E extends Static<BaseErrorSchemaType>> = Result<
>;

/**
* A simple {@link AsyncIterator} used in {@link Readable}
* A simple {@link AsyncIterableIterator} used in {@link Readable}
* that doesn't have a the extra "return" and "throw" methods, and
* the doesn't have a "done value" (TReturn).
*/
Expand All @@ -31,6 +31,7 @@ export interface ReadableIterator<T, E extends Static<BaseErrorSchemaType>> {
value: undefined;
}
>;
[Symbol.asyncIterator](): ReadableIterator<T, E>;
}

/**
Expand Down Expand Up @@ -247,6 +248,9 @@ export class ReadableImpl<T, E extends Static<BaseErrorSchemaType>>

return { done: false, value } as const;
},
[Symbol.asyncIterator]() {
return this;
},
return: () => {
this.break();

Expand Down

0 comments on commit 687fc36

Please sign in to comment.