Skip to content

Instantly share code, notes, and snippets.

@s-melnikov
Last active July 19, 2016 11:52
Show Gist options
  • Save s-melnikov/b109be08a6aaa709cf351fe463f38766 to your computer and use it in GitHub Desktop.
Save s-melnikov/b109be08a6aaa709cf351fe463f38766 to your computer and use it in GitHub Desktop.
function promise(ex) {
var e = {}, r = {}
r.then = function (resolve, reject) {
e.resolve = resolve || function() {},
e.reject = reject || function() {}
}
ex(function() { e.resolve.apply(this, arguments) },
function() { e.reject.apply(this, arguments) })
return r
}
function ajax(url) {
return promise(function(resolve, reject) {
var xhr = new XMLHttpRequest()
xhr.open('GET', url, true)
xhr.onload = function() {
if (xhr.status >= 200 && xhr.status < 400) {
resolve({
status: xhr.status,
text: function() { return xhr.responseText },
ok: true,
json: function() {
try { return JSON.parse(xhr.responseText) } catch(e) { return null }
},
xml: function() {
return xhr.responseXML
}
})
} else reject({status: xhr.status})
};
xhr.onerror = reject
xhr.send()
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment