Re: [whatwg/streams] Allow stream reader cancel() method to return bytes from queue instead of discarding them. (#1147)

> While it might be nice syntactically to have `cancel()` return any bytes left in the queue I think this can be polyfilled with,
> 
> ```js
> const finalReadPromise = reader.read();
> await reader.cancel();
> const finalRead = await finalReadPromise;
> ```

That's pretty clever! 😀 It should work in simple cases, although I'm not sure how well it would translate to more complex scenarios (e.g. pipe chains or cross-realm streams) where chunks are buffered in multiple streams.

I don't know if we want to make this easier. Perhaps we could have a reader property indicating if there are chunks available in the queue (i.e. if `[[queue]]` is non-empty)? A bit like the `EWOULDBLOCK` error code, or [Java's `InputStream.available()`](https://docs.oracle.com/en/java/javase/16/docs/api/java.base/java/io/InputStream.html#available()). But as Domenic already asked: it would help to better understand the use case. 🙂

> Would it? If there are queued bytes then shouldn't the read complete before the call to `cancel()`? I guess it depends on whether `read()` queues a task to check the queue and so can never complete "synchronously".

Correct, the specification requires `read()` to pull a chunk from the queue synchronously. All of these steps happen in the same tick: `ReadableStreamDefaultReaderRead` ➡️ `[[PullSteps]]` ➡️ Remove *entry* from `this.[[queue]]`.

However, it will only pull *one* chunk. If multiple chunks were `enqueue()`d, a single `read()` will only pull one of those chunks and there might still be chunks left in the queue by the time your example `cancel()`s the stream. That said, if you know you're dealing with a [pull source](https://streams.spec.whatwg.org/#pull-source) with HWM = 0 (which is the main use case for BYOB), then you'll never have more than one chunk in the queue... so you'd still be fine.


-- 
You are receiving this because you are subscribed to this thread.
Reply to this email directly or view it on GitHub:
https://github.com/whatwg/streams/issues/1147#issuecomment-882881832

Received on Monday, 19 July 2021 21:44:43 UTC