Skip to content

Instantly share code, notes, and snippets.

@akinjide
Last active July 7, 2017 19:47
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 akinjide/d8f090ccee340c6d8d65de62c6ac41ea to your computer and use it in GitHub Desktop.
Save akinjide/d8f090ccee340c6d8d65de62c6ac41ea to your computer and use it in GitHub Desktop.
Native HTTP Request using Promise
const get = (url) => {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.onreadystatechange = () => {
if (xhr.readyState === XMLHttpRequest.DONE) {
if (xhr.status === 200) {
resolve(JSON.parse(xhr.responseText));
} else {
reject(xhr);
}
}
};
xhr.open("GET", url, true);
xhr.send();
});
};
// ex.
get('https://api.github.com/users/akinjide')
.then((response) => {
console.log(response);
})
.catch(err => {
console.log(err)
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment