The fetch
specification states that the readable stream Body
contains the Body.bodyUsed
flag which is initially set to false
and then is set to true
with a call of any parsing method.
Here's an example:
fetch('/some/path', (res) => {
// res.body.bodyUsed === false
res.json();
// res.body.bodyUsed === true
});
If you try to call a method like res.json()
or res.text()
once again, an exception is thrown.
The question is: why that behavior is used? Why not to allow parsing that readable stream as many times as one wants? I found no explanation of the matter.
PS. In Chrome (and maybe other browsers), that flag is accessible as res.body.locked
.
The fetch
specification states that the readable stream Body
contains the Body.bodyUsed
flag which is initially set to false
and then is set to true
with a call of any parsing method.
Here's an example:
fetch('/some/path', (res) => {
// res.body.bodyUsed === false
res.json();
// res.body.bodyUsed === true
});
If you try to call a method like res.json()
or res.text()
once again, an exception is thrown.
The question is: why that behavior is used? Why not to allow parsing that readable stream as many times as one wants? I found no explanation of the matter.
PS. In Chrome (and maybe other browsers), that flag is accessible as res.body.locked
.
-
1
why that behavior is used?
because it's easy to allow multiple use usingResponse.clone()
- developer.mozilla/en-US/docs/Web/API/Response/clone – Jaromanda X Commented Oct 14, 2017 at 7:59 -
1
It would require the body to be stored in the
res
object. – Barmar Commented Oct 14, 2017 at 8:00 -
3
@JaromandaX yes, but that doesn't answer the next logical question: why to restrict it in first place and implementing
clone()
instead. – Phil Filippak Commented Oct 14, 2017 at 8:23 -
2
@PhilFilippak "but that doesn't answer the next logical question: why to restrict it in first place and implementing
clone()
instead." How do you propose to identify when aReadableStream
read procedure is plete? – guest271314 Commented Oct 14, 2017 at 8:34 -
1
clone
cannot be used (it throws) if the body has been consumed. – Armen Michaeli Commented Feb 10, 2022 at 14:50
1 Answer
Reset to default 8The question is: why that behavior is used? Why not to allow parsing that readable stream as many times as one wants?
It is possible to read Response.body
more than once by using Response.clone()