我希望在 JavaScript/jQuery 中对任意数量的可能可选的函数调用进行排队。例如,在运行第二个(或第三个、第四个等)函数或 AJAX 调用之前,我可能需要确保用户已通过身份验证并设置了 cookie。
我研究了使用最近添加的 jQuery.Deferred 来执行此操作,但发现触发调用的顺序无关紧要(真正的异步样式)。另外,我读到一旦 Deferred 实例被解析,就不可能取消解析它。
这就是我目前所处的位置。最初,我考虑将 Deferred 实例设置为已解析,然后在堆栈中出现可选函数时取消解析它。
var d = $.Deferred(),
chained = d,
d.resolve(),
div = extra.find( "div:first" );
if ( extra.attr( "requires-auth" ) != undefined && !config.user_is_authenticated )
chained = chained.pipe( authenticate );
if ( div.length )
chained = chained.pipe( prepareExtra( div ) );
// When the two optional methods are resolved, show the content
chained.done( function() {
extra.fadeIn( 500 )
} );
我的问题是,在纯 JavaScript/jQuery 中排队(0 到 N)AJAX 调用的最佳方法是什么? (不使用插件)。
来吧!
编辑 2:已解决! 下面是这方面的一些工作示例,一个不使用 AJAX,一个使用: https://gist.github.com/1021429 https://gist.github.com/1021435
最佳答案
尝试将最初的 Deferred 解析为最后一件事:
var d = $.Deferred(),
chained = d;
// optionally chain callbacks with chained = chained.pipe
if (condition) {
chained = chained.pipe(function () {
return $.ajax({...}); // Must return a new Promise
});
}
chained.done(function () {
// all chains should be processed now
});
d.resolve(); // finally, resolve the initial Deferred
关于javascript - 在 jQuery ($.Deferred) 中排队可选的 AJAX/函数调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6294564/