Skip to content

Instantly share code, notes, and snippets.

@SparK-Cruz
Created January 21, 2021 02:02
Show Gist options
  • Save SparK-Cruz/e43829874de462231fdec01957c2ba7f to your computer and use it in GitHub Desktop.
Save SparK-Cruz/e43829874de462231fdec01957c2ba7f to your computer and use it in GitHub Desktop.
Yet another browser AJAX lib
(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