Skip to content

Instantly share code, notes, and snippets.

@artemgurzhii
Last active November 18, 2016 23:58
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 artemgurzhii/fbb1b4dcad04a8a3ee4954db8fd21738 to your computer and use it in GitHub Desktop.
Save artemgurzhii/fbb1b4dcad04a8a3ee4954db8fd21738 to your computer and use it in GitHub Desktop.
Promise XMLHttpRequest function
function XHR(url) {
return new Promise((resolve, reject) => {
let request = new XMLHttpRequest();
request.open('GET', url, true);
request.send(null);
request.addEventListener('readystatechange', () => {
if (request.status === 200) {
if (request.readyState === 4) {
resolve(JSON.parse(request.response));
}
} else {
reject(`XMLHttpRequest rejected with status ${request.status}: ${request.statusText}`);
}
}, false);
});
}
// Usage
// XHR('https://www.facebook.com')
// .then(result => console.log(JSON.stringify(result)))
// .catch(error => new Error(error));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment