Last active
December 10, 2018 03:35
-
-
Save Floofies/94c3df59aae9fbe2e7faa0ddb49289bb to your computer and use it in GitHub Desktop.
A tiny XMLHttpRequest wrapper.
This file contains hidden or 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
function XHR(url = "/", verb = "GET", data = null) { | |
this.requestor = null; | |
this.url = url; | |
this.verb = verb; | |
this.data = data; | |
} | |
XHR.prototype.executor = function (resolve, reject) { | |
this.requestor.onreadystatechange = () => this.stateChange(resolve, reject); | |
this.requestor.ontimeout = () => this.timeout(resolve, reject); | |
this.requestor.onerror = reject; | |
this.requestor.open(this.verb, this.url); | |
this.requestor.setRequestHeader("X-Requested-With", "XMLHttpRequest"); | |
this.requestor.send(this.data); | |
}; | |
XHR.prototype.stateChange = function (resolve, reject) { | |
if (this.requestor.readyState !== 4) return; | |
if (this.requestor.status >= 200 && this.requestor.status < 400) resolve(this.requestor.response); | |
else reject(new Error("Failed to load \"" + this.url + "\"\nHTTP Error " + this.requestor.status + " " + this.requestor.statusText)); | |
this.requestor = null; | |
}; | |
XHR.prototype.timeout = function (resolve, reject) { | |
reject(new Error("Failed to load \"" + this.url + "\"\nRequest Timed Out")); | |
}; | |
XHR.prototype.run = function () { | |
this.requestor = new XMLHttpRequest(); | |
this.requestor.timeout = 30000; | |
this.requestor.responseType = "text"; | |
return new Promise((resolve, reject) => this.executor(resolve, reject)); | |
}; | |
function ajax(url = "/", verb = "GET", data = null) { | |
return new XHR(url, verb, data).run(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment