Skip to content

Instantly share code, notes, and snippets.

@sreekotay
Last active June 30, 2020 21:27
Show Gist options
  • Save sreekotay/3a8a3c240ad2b76a67165c666a5720ed to your computer and use it in GitHub Desktop.
Save sreekotay/3a8a3c240ad2b76a67165c666a5720ed to your computer and use it in GitHub Desktop.
function fetchXHR (url, httpMethod, body) { // httpMethod is optional
var xhr = new XMLHttpRequest();
var promise = new Promise(function (resolve, reject) {
xhr.onreadystatechange = function () {
if (xhr.readyState !== 4) return
if (xhr.status >= 200 && xhr.status < 300) resolve(xhr.response)
else reject({status: xhr.status, statusText: xhr.statusText, xhr:xhr})
}
xhr.open(httpMethod || 'GET', url, true)
xhr.send(body)
})
promise.abort = function() { xhr.abort() }
promise.xhr = xhr
return promise
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment