Skip to content

Instantly share code, notes, and snippets.

@kypflug
Last active May 26, 2016 17:09
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kypflug/f486046ba87076088742212316d0df7d to your computer and use it in GitHub Desktop.
Save kypflug/f486046ba87076088742212316d0df7d to your computer and use it in GitHub Desktop.
Making a request for a JSON resource with XHR
var xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.responseType = 'json';
xhr.onload = function() {
console.log(xhr.response);
};
xhr.onerror = function() {
console.log("Houston, we've got a problem.");
};
xhr.send();
@WebReflection
Copy link

WebReflection commented May 24, 2016

The amount of code cannot be the number one selling point, specially if the examples are written differently.

As example, why so many empty lines in this one, compared to the ultra-packed, less readable fetch counter-example?

If you want to compare the amount of code, don't you think this would be a more fair comparison?

var xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.responseType = 'json';
xhr.onload = () => console.log(xhr.response);
xhr.onerror = () => console.log("Houston, we've got a problem.");
xhr.send();

There, 6 lines of readable code that do one thing per line without side-effects.

@WebReflection
Copy link

WebReflection commented May 24, 2016

just to be counter-fair myself:

fetch(url)
  .then((response) => response.json())
  .then((jsonData) => console.log(jsonData))
  .catch(() => console.log("Houston, we've got a problem."));

So, now we can talk about less code. Doing it adding empty lines to the old example feels like somebody is cheating, maybe thinking that readers are all stupid :-(

@risseraka
Copy link

@tabatkins
Copy link

It was a trivial example. Now do two fetches, with a "both successful" callback and a "something failed" callback.

The point isn't necessarily that it's less code (tho it is, as you conceded), it's that the entire model is simpler.

@WebReflection
Copy link

WebReflection commented May 25, 2016

Simpler, sure ... and now abort a fetch ... or show me a download/upload progress .... uh wait ....

My point is that LOC as first reason to ditch anything is a very poor argument.

The two APIs do different things. Comparing them to sell Fetch is silly because fetch lacks of few things already very simple through XHR and vice-versa, XHR doesn't expose streams so it's inferior.

These are informative points. Showing extra empty lines to demonstrate how much less LOC we have now?

Meh ¯\_(ツ)_/¯

@felquis
Copy link

felquis commented May 26, 2016

Meh ¯\_(ツ)_/¯

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment