我的应用程序由复杂的数据库架构支持,外键限制很重,导致我的 JavaScript 充满了callback
处理程序。对于单个操作,例如创建新订单,可能需要多达三个 XHR 来提交所有必要的数据以进行处理。
目前,我正在以我觉得相当不雅或至少有点草率的方式处理这个问题......
/** -- PSEUDO CODE -- */
myOrder.save({
success: function()
{
/** This request handled inserting the main attributes of the model
into the database, which means it is safe to fire off additional
requests */
myOrderContents.store.sync({
success: function()
{
/** Possibly fire another request here, that is dependent on
the first two requests returning successfully, or maybe
execute code that is also dependent on these requests.
*/
}
});
},
failure: function()
{
/** Handle Failure Here */
}
});
我意识到另一种可行的方法是类似于调用一个回调方法的所有请求,然后它只会执行特定的代码块......
myOrder.save({callback: executeAfterRequests});
myOrderContents.store.sync({callback: executeAfterRequests});
myOtherObject.save({callback: executeAfterRequests});
executeAfterRequests: function()
{
if(requestA.isComplete() && requestB.isComplete() && requestC.isComplete())
{
/** Execute some code after all requests have been completed... */
}
}
鉴于 ExtJS 开发人员强烈反对同步请求,我最好的选择是扩展基本 AJAX 类并实现队列吗?或者,接受 AJAX 的本质并继续使用嵌套success
功能继续我的快乐方式?
谢谢您的意见。