javascript / expert
Snippet
Suspense-Compatible Streaming Async Iterable Reader
Adapts a JavaScript AsyncIterableIterator into a React Suspense resource mechanism. By throwing pending promises during iteration and holding fulfilled values, it seamlessly bridges async stream processing with React component suspend-and-render mechanics.
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
function wrapAsyncIterable(asyncIterable) {const iterator = asyncIterable[Symbol.asyncIterator]();let status = 'pending';let result;let suspender = iterator.next().then(res => { status = 'fulfilled'; result = res; },err => { status = 'rejected'; result = err; });return {readNext() {if (status === 'pending') throw suspender;if (status === 'rejected') throw result;if (result.done) return { done: true };const current = result.value;status = 'pending';suspender = iterator.next().then(res => { status = 'fulfilled'; result = res; },err => { status = 'rejected'; result = err; });return { done: false, value: current };}};}
react
Breakdown
1
const iterator = asyncIterable[Symbol.asyncIterator]();
Retrieves the native async iterator instance via the Symbol.asyncIterator well-known symbol.
2
if (status === 'pending') throw suspender;
Throws the active pending Promise to trigger React Suspense boundary fallback UI.
3
if (status === 'rejected') throw result;
Re-throws captured iterator rejection errors directly into React Error Boundaries.
4
suspender = iterator.next().then(...)
Advances the iterator to fetch subsequent streaming chunks and updates internal status flags.