javascript / expert
Snippet
Async Generator Control Flow with Symbol.asyncIterator for Chunked Stream Transformations in Next.js
This snippet demonstrates implementing a custom object class with an [Symbol.asyncIterator] generator protocol to control stream chunk iteration gracefully within a Next.js App Router Route Handler. By wrapping ReadableStreamDefaultReader inside an async generator, cleanup logic inside the finally block releases the stream lock cleanly upon stream completion or premature loop termination.
snippet.js
javascript
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
export class ChunkStreamConsumer {constructor(readableStream) {this.reader = readableStream.getReader();}async *[Symbol.asyncIterator]() {try {while (true) {const { done, value } = await this.reader.read();if (done) break;yield value;}} finally {this.reader.releaseLock();}}}export async function POST(req) {const consumer = new ChunkStreamConsumer(req.body);let totalBytes = 0;for await (const chunk of consumer) {totalBytes += chunk.byteLength;}return Response.json({ processedBytes: totalBytes });}
nextjs
Breakdown
1
async *[Symbol.asyncIterator]() {
Defines a custom async generator protocol allowing instance consumption via for-await-of loop.
2
const { done, value } = await this.reader.read();
Reads incoming binary chunks asynchronously from the stream reader state.
3
this.reader.releaseLock();
Ensures resource cleanup by releasing the reader lock when execution exits the generator.