Processing Stream Data in a Loop
You'll learn how to continuously read streaming response data chunk-by-chunk until the entire body is consumed.
Why Loop Over Stream Chunks?
When you get a ReadableStream reader and call read() once, you get just one chunk of data. But streams often deliver data in multiple pieces—like receiving a book page by page instead of all at once. To process the entire response body, you need to keep reading until the stream signals it's finished.
The Async Loop Pattern
After obtaining a reader with stream.getReader(), you call read() repeatedly. Each call returns a promise that resolves to an object with two properties:
done: a boolean—truewhen the stream is complete,falseotherwisevalue: aUint8Arraychunk of data (undefined when done)
Here's the standard pattern:
const response = await fetch('https://api.example.com/data');
const reader = response.body.getReader();
while (true) {
const { done, value } = await reader.read();
if (done) {
console.log('Stream complete');
break;
}
// Process the chunk (value is a Uint8Array)
console.log('Received chunk:', value.length, 'bytes');
}
The while (true) loop continues indefinitely until done becomes true, at which point you break out. Each iteration processes one chunk of the response.
Think of It Like This
Imagine a water pipe: you keep checking if water is flowing. When done is false, you collect the water (value). When done is true, the pipe is empty—you're finished.
Key Takeaway: Use an async loop with await reader.read() to continuously process stream chunks, checking done: true to know when the stream has completed.