ReadableStream.from Adapts Iterables
Adapt a sync generator into a web ReadableStream with ReadableStream.from, then consume it with async iteration.
Code
async function* rows() {
yield 'alpha';
yield 'beta';
yield 'gamma';
}
async function collect(stream) {
const values = [];
for await (const value of stream) {
values.push(value);
}
return values;
}
async function main() {
const stream = ReadableStream.from(rows());
const values = await collect(stream);
console.log('values:', values.join(','));
console.log('count:', values.length);
}
main();Output
Captured from a sandboxed run of this snippet in the build pipeline.
values: alpha,beta,gamma
count: 3How it works
ReadableStream.from Adapts Iterables reduces to the functions collect and main.
Iteration happens inside for await (const value of stream) — everything outside it runs once. Asynchronous boundaries use await, so failures surface as rejected promises at the call site instead of being swallowed.
Applying it
Signature: async function collect(stream)
The run emits 2 labeled sections — values:, count: — one per step.
The sequence collect lives in main; running the file triggers it.
Statements that matter
const values = await collect(stream);
for await (const value of stream) {
values.push(value);
}
yield 'alpha';
FAQ
- What does ReadableStream.from Adapts Iterables print when run?
- No setup needed: run the file and look for labeled lines like `values:`, `count:` in the output.
Report a problem with this exampleOpens a pre-filled issue on GitHub.