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
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.
Response.text()
is an asynchronous function. It reads the content of theResponse.body
as text. To do this, it acquires a reader from the underlyingReadableStream
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?
First invocation reads the stream but is not waited for and then another reader is attempted to be acquired.
But this should work: