Created
January 21, 2021 02:02
-
-
Save SparK-Cruz/e43829874de462231fdec01957c2ba7f to your computer and use it in GitHub Desktop.
Yet another browser AJAX lib
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 () { | |
function prmze() { | |
let thenCallback = null; | |
let catchCallback = null; | |
let child = null; | |
return { | |
ready: false, | |
then: function (callback) { | |
this.ready = true; | |
child = prmze(); | |
thenCallback = callback; | |
return child; | |
}, | |
catch: function (callback) { | |
this.ready = true; | |
child = prmze(); | |
catchCallback = callback; | |
return child; | |
}, | |
resolve: function (value) { | |
thenCallback && thenCallback(value); | |
child && child.resolve(value); | |
}, | |
fail: function (value) { | |
let cb = catchCallback; | |
if (!cb && (!child || !child.ready)) | |
cb = thenCallback; | |
cb && cb(value); | |
child && child.fail(value); | |
} | |
}; | |
} | |
function request(method, url, data) { | |
const response = prmze(); | |
const xhr = new XMLHttpRequest(); | |
xhr.open(method, url); | |
xhr.addEventListener('load', (e) => { | |
response.resolve(xhr); | |
}); | |
xhr.addEventListener('error', (e) => { | |
response.fail(xhr); | |
}); | |
data ? xhr.send(data) : xhr.send(); | |
return response; | |
} | |
window.atena = { | |
get: (url) => { | |
return request('GET', url, null); | |
}, | |
post: (url, data) => { | |
return request('POST', url, data); | |
}, | |
delete: (url) => { | |
return request('DELETE', url, null); | |
}, | |
head: (url) => { | |
return request('HEAD', url, null); | |
}, | |
put: (url, data) => { | |
return request('PUT', url, data); | |
}, | |
patch: (url, data) => { | |
return request('PATCH', url, data); | |
}, | |
options: (url) => { | |
return request('OPTIONS', url, null); | |
} | |
}; | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment