[whatwg/fetch] Pause readable stream reader (Issue #1651)

As far as I know, once you've started reading a stream from `response.body` you can't pause and resume it like you can [with node](https://nodejs.org/api/stream.html#event-pause).

I think this would be very useful. I've tested this with the below React code sending back a stream of JSON from an app I'm running locally. I thought that if I used `sleep` in a blocking way it would stop the reader from reading but I noticed that it keeps reading in the background. 

Perhaps I've made a mistake here and there is a way to achieve this in pure JS, I'd be really grateful for an example of that if so!

```javascript
import logo from "./logo.svg";
import "./App.css";

function App() {
  let pause = false;
  let cancel = false;
  function changePause() {
    pause = !pause;
  }
  function cancelStream() {
    cancel = true;
  }
  function sleep(ms) {
    return new Promise((resolve) => setTimeout(resolve, ms));
  }

  async function* iterateOverStream(stream) {
    const reader = stream.getReader();
    const decoder = new TextDecoder();

    while (true) {
      if (pause) {
        // Slow down the infinite loop repeating until pause is pressed again
        // I thought that this would pause the reader from reading but it doesn't
        // it just pauses displaying the data, the reader keeps reading in the background
        await sleep( 3 * 1000);
        continue;
      } else {
        const { done, value } = await reader.read();
        if (done) break;
        yield decoder.decode(value, { stream: !done });
        if (cancel) {
          reader.cancel();
          break;
        }
      }
    }
    reader.releaseLock();
  }

  async function readData() {
    cancel = false;
    const response = await fetch("http://localhost:5000");
    for await (const chunk of iterateOverStream(response.body)) {
      console.log(`json chunk is ${chunk}`);
    }
  }

  return (
    <div className="App">
      <header className="App-header">
        <img src={logo} className="App-logo" alt="logo" />
        <p onClick={readData}>
          Click me and check out dev tools to test stream
        </p>
        <p onClick={changePause}>Click to pause/unpause</p>
        <p onClick={cancelStream}>Click to cancel stream</p>
      </header>
    </div>
  );
}

export default App;
```

-- 
Reply to this email directly or view it on GitHub:
https://github.com/whatwg/fetch/issues/1651
You are receiving this because you are subscribed to this thread.

Message ID: <whatwg/fetch/issues/1651@github.com>

Received on Friday, 5 May 2023 13:56:59 UTC