Skip to content

Instantly share code, notes, and snippets.

@jbmoelker
Created September 28, 2017 11:22
Show Gist options
  • Save jbmoelker/54ceb2d00ae9771929c8bf8f597eee25 to your computer and use it in GitHub Desktop.
Save jbmoelker/54ceb2d00ae9771929c8bf8f597eee25 to your computer and use it in GitHub Desktop.
Fetch JSON using Promisified XMLHttpRequest
export default function fetchJson(url) {
return new Promise((resolve, reject) => {
const request = new XMLHttpRequest()
request.open('GET', url, true)
request.setRequestHeader('Accept', 'application/json')
request.onload = function() {
if (request.status >= 200 && request.status < 400) {
try {
const json = JSON.parse(request.responseText)
resolve(json)
} catch (err) {
reject(new Error('Unable to convert response to JSON'))
}
} else {
reject(request)
}
};
request.onerror = function() {
reject(request)
}
request.send()
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment