Skip to content

Commit f817723

Browse files
committed
feat: add async iter
1 parent f758cb6 commit f817723

2 files changed

Lines changed: 23 additions & 5 deletions

File tree

src/index.ts

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -114,6 +114,24 @@ class Queue<T> {
114114
*/
115115
shiftUnsafe = () => this._shift();
116116

117+
/**
118+
* Implements the async iterator protocol, allowing the queue to be consumed
119+
* in a for-await-of loop. Marks the queue as piped.
120+
* @example
121+
* for await (const item of queue) {
122+
* console.log(item);
123+
* }
124+
* @returns An async generator that yields values from the queue.
125+
*/
126+
[Symbol.asyncIterator] = async function* (
127+
this: Queue<T>,
128+
): AsyncGenerator<T, void, unknown> {
129+
this._preparePipe();
130+
131+
for (let r = await this._shift(); r !== Queue._eof; r = await this._shift())
132+
yield r as T;
133+
};
134+
117135
/**
118136
* Maps each value in the queue using the provided callback function.
119137
* @param callback The function to apply to each value in the queue.

test/test.ts

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -16,9 +16,9 @@ console.log('push one');
1616
queue.push('2');
1717
console.log('push two');
1818

19-
queue.waitForShift().then(() => console.log('1'));
20-
queue.waitForShift().then(() => console.log('2'));
19+
queue.end();
20+
for await (const item of queue) {
21+
console.log(item, 'hehe');
22+
}
2123

22-
queue.shiftUnsafe();
23-
console.log('ow');
24-
queue.shiftUnsafe();
24+
console.log('out');

0 commit comments

Comments
 (0)