javascript / expert
Snippet
Consuming ReadableStream Response Chunks via Custom Async Iterators
Leverages async generator functions and for-await-of loop control flow to consume HTTP stream responses sequentially inside Svelte component logic while guaranteeing reader lock release.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
export async function* streamChunks(response) {const reader = response.body.getReader();const decoder = new TextDecoder();try {while (true) {const { done, value } = await reader.read();if (done) break;yield decoder.decode(value, { stream: true });}} finally {reader.releaseLock();}}export async function consumeStreamInSvelte(response, onChunk) {for await (const chunk of streamChunks(response)) {onChunk(chunk);}}
svelte
Breakdown
1
export async function* streamChunks(response) {
Declares an async generator function returning an AsyncIterable iterator interface.
2
yield decoder.decode(value, { stream: true });
Decodes binary chunk buffer into string content and yields control back to consumer loop.
3
reader.releaseLock();
Releases network stream reader lock inside finally block regardless of iterator termination method.
4
for await (const chunk of streamChunks(response)) {
Iterates asynchronously over incoming stream text chunks in non-blocking event loop ticks.