Skip to content

Commit

Permalink
Add example for request + "Garbage Collection" (#3916)
Browse files Browse the repository at this point in the history
* Add example for `request` + "Garbage Collection"

* `dump` never throws without a signal

* fix code (response !== res)

* async await

* add "force consumption of body" comment
  • Loading branch information
WTCT-TOP authored Dec 8, 2024
1 parent bfdfcc0 commit 03edf68
Showing 1 changed file with 15 additions and 9 deletions.
24 changes: 15 additions & 9 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down

0 comments on commit 03edf68

Please sign in to comment.