We have an AJAX web application, and a common pattern we have is a number of ajax calls that call one after the other. This is common when we save something with multiple attached entities. An example might be saveCustomer() --> saveCustomerAddress() --> saveCustomersOrder().
We currently have it so that when methodA() succeeds, ie the first method, it calls methodB(), and so forth (See code below). The disadvantage to this pattern is that it is really hard to see what is going on. If you read methodA() you have no idea from reading the method name that it also calls methodB() and methodC(). The other disadvantage is that if you want to change the chaining you have to rewrite a lot of code, and if you want to just call a method individually, it can't be done because it will call methods downstream.
function Tester() {
this.url = 'https://public.opencpu.org/ocpu/library/';
this.save = function() {
this.methodA();
}
this.methodA = function () {
var self = this;
$.ajax({
url: self.url,
async: true
}).always(function (processedDataOrXHRWrapper, textStatus, xhrWrapperOrErrorThrown) {
//check for errors... and if OK
alert('A OK');
self.methodB();
})
}
this.methodB = function () {
var self = this;
$.ajax({
url: self.url,
async: true
}).always(function (processedDataOrXHRWrapper, textStatus, xhrWrapperOrErrorThrown) {
//check for errors... and if OK
alert('B OK');
self.methodC();
})
}
this.methodC = function () {
var self = this;
$.ajax({
url: self.url,
async: true
}).always(function (processedDataOrXHRWrapper, textStatus, xhrWrapperOrErrorThrown) {
//OK
alert('C OK');
})
}
}
new Tester().save();
I am scratching my head trying to figure out a better pattern. I figured you could wrap up the later methods in callback functions, and then somehow pass them through each method but I'm not really sure how to approach this.
Is anyone aware of a common type of pattern where you can remove the method dependencies when chaining methods?