skip to Main Content

If I do something like:

    fetch(...)
    .then((res) => {
        console.log(res.text(), res.text())
    })

I’ll get: Failed to execute ‘text’ on ‘Response’: body stream already read

Why does the readablestream get locked? I don’t get the reasoning behind disallowing this

2

Answers


  1. That’s the entire idea of a stream. You consume it and retain only the information that you need.

    This gives you access to the data as it becomes available, and avoids having to keep everything in memory.

    Login or Signup to reply.
  2. Response.text() is an asynchronous function. It reads the content of the Response.body as text. To do this, it acquires a reader from the underlying ReadableStream and once this reader has been acquired, the stream gets locked to it. While the stream is locked, no other reader can be acquired until this one is released.

    So what are you doing?

    console.log(res.text(), res.text())

    First invocation reads the stream but is not waited for and then another reader is attempted to be acquired.

    But this should work:

    let text1 = await res.text()
    console.log(text1)
    let text2 = await res.text()
    console.log(text2)
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search