Last active
March 9, 2016 09:25
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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