MDN self-hosted library · e01.org

ReadableStream: from() static method

Runnable notebook: every JavaScript, HTML and CSS example on this page executes in a sandboxed local frame. Nothing leaves the browser.

html
<pre id="log"></pre>
js
const logElement = document.getElementById("log");
function log(text) {
  logElement.innerText += `${text}\n`;
}
js
if (!ReadableStream.from) {
  log("ReadableStream.from() is not supported");
}
js
// Define an asynchronous iterator
const asyncIterator = (async function* () {
  yield 1;
  yield 2;
  yield 3;
})();

// Create ReadableStream from iterator
const myReadableStream = ReadableStream.from(asyncIterator);
js
consumeStream(myReadableStream);

// Iterate a ReadableStream asynchronously
async function consumeStream(readableStream) {
  for await (const chunk of readableStream) {
    // Do something with each chunk
    // Here we just log the values
    log(`chunk: ${chunk}`);
  }
}