我如何知道上次异步完成的时间?
我有这样的事情:
for (var i=0;i<result.qry.ROWCOUNT;i++) { myAsync(i); }
我怎么知道我的所有异步函数何时完成执行?
冒着有人回复“需要更多jQuery!”的风险,我可以使用jQuery promise对象吗? 或推迟或类似的东西?
跟踪未完成的异步调用次数。 当每个完成时,减少你的计数器。 当你到0时,你就是最后一个回调。
var asyncsLeft = 0; for (var i=0;i<10;++i){ asyncsLeft++; doSomethingAsyncWithCallback(function(){ // This should be called when each asynchronous item is complete if (--asyncsLeft==0){ // This is the last one! } }); }
由于JavaScript的单线程特性,没有潜在的竞争条件,您可能会在所有异步调用排队之前调用回调。 如果您愿意,可以在doSomethingAsynchronous
之后放置asyncsLeft++
调用。
我就是这样做的:
//Do stuff up here to get records var rowCount = result.qry.ROWCOUNT, //Save the row count asyncCount = 0, //The count of complete async calls asyncCallback = function() { //To be called whenever an async operation finishes asyncCount++; //Increment the row counter if (asyncCount >= rowCount) { //Do stuff when they're all finished } }; for (var i=0;i
在jQuery中,有一个$.ajaxStop
函数在最后一个Ajax运行后运行。
如果您使用的是jQuery,还可以使用ajaxSend
和ajaxComplete
方法将计数器代码与调度代码分开。
var ajaxPending = 0; function ajax_changed(indicator, pending) { if (pending) $(indicator).show(); else $(indicator).hide(); } $('#loading-indicator').ajaxSend(function() { ajax_changed(this, ++ajaxPending); }); $('#loading-indicator').ajaxComplete(function() { ajax_changed(this, --ajaxPending); });
使用回调函数:
for (var i=0;i