I've gotten fed up of writing boilerplate code for managing Ajax calls, and this is the manager class I've come up with
The concept is that it standardizes the interface for RESTful calls, prevents duplicate calls from firing via a request key, also simplifies waiting for a call to complete.
function AjaxManager() {
this.processes = {};
this.ajax = (label, uri, settings, success, fail) => {
console.log({
ajax: {
label,
uri,
settings
}
});
this.abort(label);
this.processes[label] = $.ajax(
uri,
settings
).done((response) => {
console.log({
label,
success: "success",
response
});
if (success) {
success(response);
}
}).fail((response) => {
console.log({
label,
success: "fail",
response
});
if (fail) {
fail(response);
}
}).always(() => {
console.log("cleanup " + label);
this.processes[label] = null;
});
}
this.post = (label, uri, data, success, fail) => {
this.ajax(label, uri, {
method: "POST",
data: data
}, success, fail);
}
this.get = (label, uri, data, success, fail) => {
this.ajax(label, uri, {
method: "GET",
data: data
}, success, fail);
}
this.put = (label, uri, data, success, fail) => {
this.ajax(label, uri, {
method: "PUT",
data: JSON.stringify(data),
contentType: "application/json",
dataType: "json",
}, success, fail);
}
this.delete = (label, uri, data, success, fail) => {
this.ajax(label, uri, {
method: "DELETE",
data: data
}, success, fail);
}
this.wait = (label, callback) => {
if (this.processes[label]) {
this.processes[label].then(callback);
} else {
callback();
}
}
this.abort = (label) => {
if (this.processes[label]) {
this.processes[label].abort();
}
}
}
It looks to be working correctly but I wondered if you guys could give it a once over and check for anything I've missed that needs improving or fixing.