Skip to content

Instantly share code, notes, and snippets.

@Xom
Created February 26, 2017 04:04
Show Gist options
  • Save Xom/e27ab0b98a2a12f1bf479c6b8751a402 to your computer and use it in GitHub Desktop.
Save Xom/e27ab0b98a2a12f1bf479c6b8751a402 to your computer and use it in GitHub Desktop.
XMLHttpRequest wrapped in ES6 Promise
// https://github.com/mdn/js-examples/blob/master/promises-test/index.html
xhr = function(url, responseType) {
return new Promise(function(resolve, reject) {
var request = new XMLHttpRequest();
request.open('GET', url, true);
request.responseType = responseType;
request.onload = function() {
if (request.status === 200) {
resolve(request.response);
} else {
reject(Error(`${url} failed to load; error code: ${request.statusText}`));
}
};
request.onerror = function() {
reject(Error(`${url} failed to load; there was a network error.`));
};
request.send();
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment