【发布时间】:2014-09-10 13:31:32
【问题描述】:
我们有一个 AJAX Web 应用程序,我们有一个常见的模式是多个 ajax 调用一个接一个地调用。当我们保存带有多个附加实体的东西时,这很常见。一个例子可能是 saveCustomer() --> saveCustomerAddress() --> saveCustomersOrder()。
我们目前有这样当methodA() 成功时,即第一个方法,它调用methodB(),等等(见下面的代码)。这种模式的缺点是很难看到发生了什么。如果您阅读 methodA(),您不会从方法名称中了解到它还调用了 methodB() 和 methodC()。另一个缺点是,如果你想改变链接,你必须重写很多代码,如果你只想单独调用一个方法,那是做不到的,因为它会调用下游的方法。
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();
我正在挠头,试图找出更好的模式。我想你可以将后面的方法封装在回调函数中,然后以某种方式将它们传递给每个方法,但我不确定如何处理。
是否有人知道在链接方法时可以删除方法依赖项的常见模式类型?
【问题讨论】:
-
使用承诺。 jQuery 有它,或者任何其他库。看这里:stackoverflow.com/questions/11539605/chain-of-jquery-promises 或这里dotnetcurry.com/showarticle.aspx?ID=1022
-
或者,不太高级,只使用回调......
标签: javascript ajax design-patterns