-
Let's say I want to add some basic validation to const fetchAndValidate = async (resource, options) => {
const res = await fetch(resource, { ...options, signal: ac.signal });
if (!res.ok) throw new Error(`HTTP ${res.status} - ${res.statusText}`);
return res;
}; It's naive because we never consume the body. Now if I understand correctly, there are two solutions:
const fetchAndValidate = async (resource, options) => {
const res = await fetch(resource, options);
if (!res.ok) {
for await (const _ of res.body) {
}
throw new Error(`HTTP ${res.status} - ${res.statusText}`);
}
return res;
};
const fetchAndValidate = async (resource, options) => {
const ac = new AbortController();
const res = await fetch(resource, { ...options, signal: ac.signal });
if (!res.ok) {
ac.abort()
throw new Error(`HTTP ${res.status} - ${res.statusText}`);
}
return res;
}; The second one seems more reasonable to me as we don't download data we don't really need, but I wanna make sure it is equally safe to use in terms of garbage collection, connection re-use etc. So, which solution would you choose and why? |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 8 replies
-
AFAIA, both have a similar impact on the way the whole Meanwhile, the first option requires you to iterate and wait for each chunk to be consumed (using an Given their effects, both are somehow interchangeable. And I'd have a preference for the latter. |
Beta Was this translation helpful? Give feedback.
-
I would recommend the following: async function dump(body) {
try {
let limit = 1e5;
for await (const buf of body) {
limit -= buf.byteLength;
if (limit < 0) {
return;
}
}
} catch {
// Do nothing...
}
}
const fetchAndValidate = async (resource, options) => {
const res = await fetch(resource, options);
if (!res.ok) {
dump(res.body)
throw new Error(`HTTP ${res.status} - ${res.statusText}`);
}
return res;
}; That way you don't lose keep-alive connections for small replies. |
Beta Was this translation helpful? Give feedback.
I would recommend the following:
That way you don't lose keep-alive connections for small replies.