Streaming with promises lets you show data bit by bit as it arrives, instead of waiting for everything to load. This makes apps feel faster and smoother.
Streaming with promises in Svelte
let dataPromise = fetch('url').then(response => { const reader = response.body.getReader(); return new ReadableStream({ start(controller) { function push() { reader.read().then(({ done, value }) => { if (done) { controller.close(); return; } controller.enqueue(value); push(); }); } push(); } }); });
This code uses fetch to get data and reads it in chunks using a ReadableStream.
The reader.read() method returns a promise that resolves with a chunk of data or signals the end.
let streamPromise = fetch('/api/data').then(res => res.body);
let textStream = fetch('/api/text').then(async res => { const reader = res.body.getReader(); let result = ''; while(true) { const { done, value } = await reader.read(); if (done) break; result += new TextDecoder().decode(value, { stream: true }); } return result; });
let jsonStream = fetch('/api/json').then(async res => { const reader = res.body.getReader(); let chunks = []; while(true) { const { done, value } = await reader.read(); if (done) break; chunks.push(value); } const full = new Uint8Array(chunks.flatMap(c => Array.from(c))); return JSON.parse(new TextDecoder().decode(full)); });
This Svelte component fetches a post and streams its text content. It updates the UI as chunks arrive, showing a loading message until done.
<script> import { onMount } from 'svelte'; let streamedText = ''; let loading = true; onMount(async () => { const response = await fetch('https://jsonplaceholder.typicode.com/posts/1'); const reader = response.body.getReader(); const decoder = new TextDecoder(); while(true) { const { done, value } = await reader.read(); if (done) break; streamedText += decoder.decode(value, { stream: true }); } loading = false; }); </script> <main> {#if loading} <p>Loading content...</p> {:else} <pre>{streamedText}</pre> {/if} </main>
Streaming lets users see data faster, but handling partial data requires careful UI updates.
Always handle errors and network issues when working with streams.
Use TextDecoder with the stream: true option to decode chunks properly.
Streaming with promises helps show data bit by bit for faster user feedback.
Use fetch with ReadableStream and reader.read() to get chunks.
Update your UI as chunks arrive to improve user experience.
Practice
Solution
Step 1: Understand streaming with promises
Streaming lets you process data as it arrives, not waiting for all data.Step 2: Connect streaming to user experience
Showing data bit by bit gives faster feedback, improving user experience.Final Answer:
It allows showing data bit by bit for faster user feedback. -> Option AQuick Check:
Streaming = faster feedback [OK]
- Thinking streaming waits for full data
- Confusing streaming with caching
- Believing UI updates only after full promise resolves
Solution
Step 1: Identify how to access the stream reader
The fetch response has abodyproperty which is a ReadableStream.Step 2: Use the correct method to get the reader
CallinggetReader()onresponse.bodyreturns the reader.Final Answer:
const reader = response.body.getReader(); -> Option BQuick Check:
Use response.body.getReader() [OK]
- Calling getReader() directly on response
- Using non-existent methods like readableStream()
- Confusing response.body with response itself
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();Solution
Step 1: Understand reader.read() output
reader.read() returns a promise resolving to an object withvalue(chunk) anddone(boolean).Step 2: Decode the first chunk
The code decodes the first chunk's bytes to text and logs it.Final Answer:
The first chunk of data from the response decoded as text. -> Option AQuick Check:
reader.read() gives first chunk [OK]
- Assuming reader.read() returns full response
- Expecting reader.read() to return undefined value
- Confusing promise with direct value
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);
}
}Solution
Step 1: Check how getReader() is called
getReader() must be called on response.body, not on response itself.Step 2: Identify the error cause
Calling response.getReader() will cause a runtime error because response has no such method.Final Answer:
Calling getReader() directly on response instead of response.body. -> Option CQuick Check:
Use response.body.getReader() [OK]
- Calling getReader() on response
- Forgetting to decode chunks
- Thinking while(true) always causes infinite loop
Solution
Step 1: Understand UI reactivity in Svelte
Svelte updates the UI when reactive variables or stores change.Step 2: Choose a method to update UI per chunk
Using a writable store to append each chunk triggers UI updates as data arrives.Step 3: Why other options fail
Waiting for all chunks delays UI update; setTimeout delays unnecessarily; local variable changes without binding won't update UI.Final Answer:
Use a writable store to append each decoded chunk and bind it to the UI. -> Option DQuick Check:
Writable store + binding = live UI updates [OK]
- Updating local variables without reactive binding
- Waiting for full data before UI update
- Using timers instead of reactive stores
Ready to prove it?
Pass the test and this pattern moves unknown
