Skip to content

Instantly share code, notes, and snippets.

@cvan
Created June 3, 2015 04:29
Show Gist options
  • Save cvan/224ecd7b4bb5872cf23a to your computer and use it in GitHub Desktop.
Save cvan/224ecd7b4bb5872cf23a to your computer and use it in GitHub Desktop.
if `fetch` ain't available, use this simple XHR wrapper (or use a polyfill)
function get(url, data, format) {
return new Promise(function (resolve, reject) {
var req = new XMLHttpRequest();
req.open('GET', url);
req.responseType = format || 'json';
req.onload = function() {
// It could be a successful response but not an OK one (e.g., 3xx, 4xx).
if (req.status === 200) {
resolve(req.response);
} else {
reject(Error(req.statusText));
}
};
req.onerror = function() {
reject(Error('Network Error'));
};
req.send(data);
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment