-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
pop.ts
33 lines (33 loc) · 888 Bytes
/
pop.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
/**
* Reads the next chunk from a readable stream.
*
* ```ts
* import { pop } from "@core/streamutil/pop";
*
* const reader = new ReadableStream<number>({
* start(controller) {
* controller.enqueue(1);
* controller.enqueue(2);
* controller.enqueue(3);
* controller.close();
* },
* });
*
* console.log(await pop(reader)); // 1
* console.log(await pop(reader)); // 2
* console.log(await pop(reader)); // 3
* console.log(await pop(reader)); // null
* ```
*
* @param stream The stream to read from.
* @returns A promise that resolves with the next chunk from the stream or null if the stream is closed.
*/
export async function pop<T>(stream: ReadableStream<T>): Promise<T | null> {
const reader = stream.getReader();
const result = await reader.read();
reader.releaseLock();
if (result.done) {
return null;
}
return result.value;
}