Reputation: 78850
I have some code that wants to issue a request and check whether the request is successful, but it does not care about the response body:
async function doTheThing() {
const response = await fetch(someUrl, { method: 'POST' });
if (!response.ok) {
throw new Error(`Request failed with status ${response.status}`);
}
}
As I understand it, the response body is not downloaded yet at this point. If we leave it hanging and don't follow up with something like:
const body = await response.json();
...will the request/response remain open and waiting until perhaps GC occurs? If so, is there a way to cleanly ignore the rest of the response stream without causing issues?
Upvotes: 2
Views: 2747
Reputation: 2019
You can just do a HEAD
if it doesn't have to be a POST
and you just want to check if you'll receive a 400
or 500
series error
https://developers.google.com/web/ilt/pwa/working-with-the-fetch-api#example_head_requests
Example: HEAD requests By default fetch uses the GET method, which retrieves a specific resource, but other request HTTP methods can also be used.
HEAD requests are just like GET requests except the body of the response is empty. You can use this kind of request when all you want the file's metadata, and you want or need the file's data to be transported.
If you are stuck with a POST
request, it's controlled on server-side and you will receive whatever the server returns, there's no web standard that dictates you can tell the server to not send anything, so the server would have to be explicitly written to allow this behaviour.
If you do not care, the GC will run its course once you've exited this particular scope and response
is no longer needed. You do not need to await
it or anything but it will download in the background (held in memory) and then thrown away when GC runs.
Upvotes: 1
Reputation: 1073
will the request/response remain open and waiting until perhaps GC occurs?
In short, no.
const body = await response.json();
instructs your code to wait until the response body is downloaded, it does not trigger the body download. Unless there is a reason not to, the response body stream will download the content and then close.
You can read about the process in the fetch spec.
It is possible to abort a fetch request after it has been started, but this is not recommended due to issues with browser support. See How do I cancel an HTTP fetch() request?
Upvotes: 1