From 03edf684aaf97b8bc4c1d7296d9fc3ae77afe7ff Mon Sep 17 00:00:00 2001 From: WTCT-TOP Date: Sun, 8 Dec 2024 04:47:02 -0500 Subject: [PATCH] Add example for `request` + "Garbage Collection" (#3916) * Add example for `request` + "Garbage Collection" * `dump` never throws without a signal * fix code (response !== res) * async await * add "force consumption of body" comment --- README.md | 24 +++++++++++++++--------- 1 file changed, 15 insertions(+), 9 deletions(-) diff --git a/README.md b/README.md index e856a3f41f8..b47a5fe367c 100644 --- a/README.md +++ b/README.md @@ -281,17 +281,23 @@ stalls or deadlocks when running out of connections. ```js // Do -const headers = await fetch(url) - .then(async res => { - for await (const chunk of res.body) { - // force consumption of body - } - return res.headers - }) +const { body, headers } = await fetch(url); +for await (const chunk of body) { + // force consumption of body +} // Do not -const headers = await fetch(url) - .then(res => res.headers) +const { headers } = await fetch(url); +``` + +The same applies for `request` too: +```js +// Do +const { body, headers } = await request(url); +await res.body.dump(); // force consumption of body + +// Do not +const { headers } = await request(url); ``` However, if you want to get only headers, it might be better to use `HEAD` request method. Usage of this method will obviate the need for consumption or cancelling of the response body. See [MDN - HTTP - HTTP request methods - HEAD](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/HEAD) for more details.