Last active
July 7, 2017 19:47
-
-
Save akinjide/d8f090ccee340c6d8d65de62c6ac41ea to your computer and use it in GitHub Desktop.
Native HTTP Request using Promise
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
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