Performance: Streaming with promises
This affects how quickly content appears on screen by allowing partial data to render as it arrives, improving perceived load speed.
let stream = fetch('/api/data').then(res => { const reader = res.body.getReader(); return new ReadableStream({ start(controller) { function push() { reader.read().then(({done, value}) => { if (done) { controller.close(); return; } controller.enqueue(value); push(); }); } push(); } }); }); // In Svelte, read the stream and update reactive state (e.g., array store) as chunks arrive to render progressively
let data; fetch('/api/data').then(res => res.json()).then(json => { data = json; // render UI only after all data is fetched });
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Full data fetch before render | Single batch DOM update | 1 reflow after data load | Single paint after full data | [X] Bad |
| Streaming data with promises | Incremental DOM updates | Multiple small reflows | Multiple smaller paints | [OK] Good |
body property which is a ReadableStream.getReader() on response.body returns the reader.async function fetchData() {
const response = await fetch('/data');
const reader = response.body.getReader();
const { value, done } = await reader.read();
console.log(new TextDecoder().decode(value));
}
fetchData();value (chunk) and done (boolean).async function load() {
const response = await fetch('/api');
const reader = response.getReader();
while(true) {
const { value, done } = await reader.read();
if(done) break;
console.log(value);
}
}Pass the test and this pattern moves unknown