I'm implementing my own fetch method that uses the fetch API.
While doing this I've encountered a raised error that I cannot explain.
The code fragment looks like this:
const response: Response = await fetch(url, options);
const { json } = response;
return json();
The problem is that this code triggers a promise rejection:
TypeError: Failed to execute 'json' on 'Response': body stream is locked
I know that the json method can only be called once, which it does.
The fetch itself doesn't fail. If I return directly response.json(), no rejection arises.
My question is why using the destructuring assignment on the response object, locks the body of the response which is a ReadableStream.
The reason this happens is that destructuring the object results in decoupling the json method from the original scope of the response.
One solution would be:
const response: Response = await fetch(url, options);
const { json } = response;
return json.bind(response)();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With