Skip to content

Is it better to consume not needed body or abort the request? #2194

Closed Answered by ronag
Dzieni asked this question in Q&A
Discussion options

You must be logged in to vote

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.

Replies: 2 comments 8 replies

Comment options

You must be logged in to vote
3 replies
@Dzieni
Comment options

@metcoder95
Comment options

@metcoder95
Comment options

Comment options

You must be logged in to vote
5 replies
@Dzieni
Comment options

@ronag
Comment options

@Dzieni
Comment options

@jdalton
Comment options

@metcoder95
Comment options

Answer selected by Dzieni
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
4 participants