我继承了JavaScript代码,其中Ajax处理程序的成功回调会启动另一个Ajax调用,而成功回调可能会也可能不会启动另一个Ajax调用。这导致了深度嵌套的匿名函数。也许有一种巧妙的编程模式可以避免深度嵌套,并且更加干燥。此外,还有在整个函数中使用的内部变量myVar1和myVar2的问题。
jQuery.extend(Application.Model.prototype, {
process: function() {
var myVar1;
// processing using myVar1;
jQuery.ajax({
url:myurl1,
dataType:'json',
success:function(data) {
var myVar2;
// process data using myVar1, set state of myVar2,
// then send it back
jQuery.ajax({
url:myurl2,
dataType:'json',
success:function(data) {
// do stuff with myVar1 and myVar2
if(!data.ok) {
jQuery.ajax({
url:myurl2,
dataType:'json',
success:mycallback
});
}
else {
mycallback(data);
}
}
});
}
});
}
});发布于 2010-04-02 17:03:36
多亏了链接提示和this comment,我得到了以下解决方案。我已经测试过了,它工作正常。可能存在一些作用域问题,您可以从中重构一个通用的ChainAjax类。但就目前而言,这是可以的。
jQuery.extend(MyApplication.Model.prototype, {
process: function() {
// private class for executing the Ajax calls
var myAjaxCalls = function(options) {
this.options = options;
this.myVar1 = null;
this.myVar2 =null;
}
jQuery.extend(myAjaxCalls.prototype, {
process1:function(data) {
// processsing using this.myVar1
this.myVar1 = 5;
return true;
},
process2:function(data) {
this.myVar2 = 6;
if(data.ok) {
mycallback(data);
}
else {
return true;
}
},
process3:function(data) {
// Process this.myVar1 and this.myVar
mycallback(data);
return false;
},
chainAjax:function() {
if(this.options.length > 0) {
var opt = this.options.shift();
var that = this;
jQuery.ajax({
url:opt.url,
success:function(data) {
if(that[opt.callback](data)) {
that.chainAjax();
}
}
});
}
}
});
// End private class
var calls = new myAjaxCalls([
{url:'http://localhost/', callback:'process1'},
{url:'http://localhost/', callback:'process2'},
{url:'http://localhost/', callback:'process3'}
]);
calls.chainAjax();
}
});更新:我发现了this nice presentation,它也处理有用的编程模式和最佳实践。
更新2012:同时,有几个库可用于使用异步函数模拟同步流:q、stratified.js和streamline.js
发布于 2010-04-02 08:44:02
不需要所有的回调都是匿名的和内联定义的,你可以在其他地方声明它们,在指定回调时只使用函数名。
发布于 2010-04-02 09:28:11
我建议创建一个名为"chain ajax“的小工具。你按你想要的顺序给它,然后再发射。它会将ajax链接到成功,直到所有的逻辑都用完。它将帮助你停止重复自己,只表示你想要做的事情的逻辑模型,而不是单调的编码。
https://stackoverflow.com/questions/2564486
复制相似问题