javascript / expert
Snippet
Custom Async Generator Paging within Svelte Reactive Effect Loops
Async generators decouple page retrieval from UI consumers. Combining async iteration with Svelte 5 state runes allows progressive stream updates while controlling cancellation flow via AbortSignals.
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
export async function* fetchStreamedBatches(endpoint, signal) {let offset = 0;while (!signal.aborted) {const response = await fetch(`${endpoint}?offset=${offset}`, { signal });const { items, hasMore } = await response.json();if (!items.length) break;yield items;if (!hasMore) break;offset += items.length;}}export function createStreamController(endpoint) {let items = $state([]);let loading = $state(false);async function consume(signal) {loading = true;for await (const batch of fetchStreamedBatches(endpoint, signal)) {items = [...items, ...batch];}loading = false;}return { get items() { return items; }, get loading() { return loading; }, consume };}
svelte
Breakdown
1
export async function* fetchStreamedBatches(endpoint, signal) {
Defines an async generator producing arrays of items sequentially until exhaustion or abort.
2
for await (const batch of fetchStreamedBatches(endpoint, signal)) {
Asynchronously iterates over stream chunks in sequence as network responses complete.
3
items = [...items, ...batch];
Triggers fine-grained reactive updates in Svelte by appending newly arrived batch items.