Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why a "Failed to execute 'json' on 'Response'" error is raised after destructuring the response object

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.

like image 953
Marian Tarlungeanu Avatar asked Nov 30 '25 00:11

Marian Tarlungeanu


1 Answers

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)();

like image 153
Marian Tarlungeanu Avatar answered Dec 02 '25 05:12

Marian Tarlungeanu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!