Re: [whatwg/streams] Cancelling and exception handling async iteration of ReadableStreams (Issue #1255)

> 1. What is the "right way" to cancel a stream read during async iteration from a button press?

The easiest way would be to `break` out of the loop. This will call `return()` on the async iterator, which will cancel a `ReadableStream` as [per spec](https://streams.spec.whatwg.org/#rs-asynciterator):
> By default, calling the async iterator’s `return()` method will also [cancel](https://streams.spec.whatwg.org/#cancel-a-readable-stream) the stream. To prevent this, use the stream’s `values()` method, passing true for the [`preventCancel`](https://streams.spec.whatwg.org/#dom-readablestreamiteratoroptions-preventcancel) option.

You can use an `AbortController` for this: check if the signal is aborted in each iteration, and `abort()` when the button is clicked.
```javascript
const controller = new AbortController();
button.addEventListener('click', () => controller.abort());
logChunks(mystream, { signal: controller.signal });

async function logChunks(readableXX, { signal }) {
  for await (const chunk of readableXX) {
    if (signal.aborted) throw signal.reason;
    bytes += chunk.length;
    logConsumer( `Chunk: ${chunk}. Read ${bytes} characters.`);
  }
}
```

> 2. How are you supposed to handle errors from the source - e.g. a TypeError or a network error or something? I tried putting try/catch around the logChunks() above and various other places but I don't seem to be able to catch them.

Hmm, that's odd. An error *should* cause `next()` to reject, which in turn should make the `for await..of` loop throw. 😕 

Could your provide a minimal reproduction case for this?

> 3. What is the recommended way to handle the case of a browser that does not support this feature? Is there a polyfill on the Internet that we should point users to?

Yes, there's [web-streams-polyfill](https://github.com/MattiasBuelens/web-streams-polyfill) and [sd-streams](https://github.com/stardazed/sd-streams).

> 4. Tracking bugs seem to indicate this is not yet in Safari or Chrome. Do you happen to know if Deno/NodeJS support this, and if so, whether it is compatible to the streams spec?

Indeed, there are no browsers that ship an implementation yet. But both [NodeJS](https://nodejs.org/api/webstreams.html#async-iteration) and [Deno](https://deno.land/api@v1.30.3?s=ReadableStream#method__Symbol_asyncIterator__6) already have full support and are fully compliant. 🙂

-- 
Reply to this email directly or view it on GitHub:
https://github.com/whatwg/streams/issues/1255#issuecomment-1421672493

You are receiving this because you are subscribed to this thread.

Message ID: <whatwg/streams/issues/1255/1421672493@github.com>

Received on Wednesday, 8 February 2023 00:04:09 UTC