我怎么知道上次异步完成的时间?

时间:2012-01-24 19:44:00

标签: javascript jquery asynchronous

我有这样的事情:

for (var i=0;i<result.qry.ROWCOUNT;i++) {
  myAsync(i);
}

我如何知道我的所有异步功能何时完成执行?

冒着有人回复“需要更多jQuery!”的风险,我可以使用jQuery promise对象吗?或推迟或类似的东西?

5 个答案:

答案 0 :(得分:9)

跟踪未完成的异步调用次数。当每个完成时,减少你的计数器。当你到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的单线程特性,没有潜在的竞争条件,您可能会在所有异步调用排队之前调用回调。如果您愿意,可以在asyncsLeft++后面doSomethingAsynchronous拨打电话是安全的。

答案 1 :(得分:2)

我就是这样做的:

//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<rowCount;i++) {
  myAsync(i, asyncCallback);
}

function myAsync(index, completeCallback) {
    //Do async stuff with index
    //Call completeCallback when async stuff has finished or pass it
    // into the async function to be called
}

答案 2 :(得分:1)

在jQuery中,有一个$.ajaxStop函数在最后一个Ajax运行后运行。

答案 3 :(得分:1)

如果您使用的是jQuery,还可以使用ajaxSendajaxComplete方法将计数器代码与调度代码分开。

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);
});

答案 4 :(得分:-2)

使用回调函数:

for (var i=0;i<result.qry.ROWCOUNT;i++) {
  myAsync(i, myCallback);
}

function myCallback(i){
  //set result.qry.ROWCOUNT to a var somewhere above if it's not available in this scope
  if(i == (result.qry.ROWCOUNT - 1)){
     //now you know you're actually done with all requests
  }
}
function myAsync(i,callback){
  ///do work
  callback(i);
}