Created
September 28, 2017 11:22
-
-
Save jbmoelker/54ceb2d00ae9771929c8bf8f597eee25 to your computer and use it in GitHub Desktop.
Fetch JSON using Promisified XMLHttpRequest
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
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