Skip to content

Instantly share code, notes, and snippets.

@eneko89
Last active March 9, 2016 09:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eneko89/293bcf4c45c07081a8a8 to your computer and use it in GitHub Desktop.
Save eneko89/293bcf4c45c07081a8a8 to your computer and use it in GitHub Desktop.
Fetches data from a JSON API through HTTP GET (XMLHttpRequest). It does not make a request to the same URL if the previous has not finished. Those requests are coalesced and their callbacks receive the same result.
// Variable to track requests and their callbacks so that httpGet()
// does not make a request to the same URL if the previous has not
// finished.
var requests = {};
/**
* Fetches data from a JSON API through HTTP GET (XMLHttpRequest).
*
* Requests to the same URL before the previous one completes are
* coalesced and their callbacks receive the same result.
*
* @param {String} url URL to hit.
*
* @param {Function} onLoad Called when the request completes
* with the signature onLoad(err, res),
* where 'res' is the response parsed
* as Object and 'err' null if request
* succeeded. Else, it will contain an
* HTTP errcode or -1.
*/
function httpGet(url, onLoad) {
var request = new XMLHttpRequest();
if (!requests[url]) {
requests[url] = { callbacks: [onLoad] };
request.open('GET', url, true);
request.onload = function() {
var callbacks = requests[url].callbacks;
requests[url] = null;
if (request.status >= 200 && request.status < 400) {
while (callbacks.length) {
callbacks.pop()(null, JSON.parse(request.responseText));
}
} else {
while (callbacks.length) {
callbacks.pop()(request.status);
}
}
};
request.onerror = function() {
var callbacks = requests[url].callbacks;
requests[url] = null;
while (callbacks.length) {
callbacks.pop()(-1);
}
};
request.send();
} else {
requests[url].callbacks.push(onLoad);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment