我怎么知道最后一次异步是什么时候完成的

How do I know when the last async is done?

本文关键字:什么时候 最后一次 异步 我怎么知道      更新时间:2023-09-26

我有这样的东西:

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的单线程特性,在所有异步调用排队之前,不存在可能调用回调的潜在竞争条件。如果您愿意,将asyncsLeft++调用放在doSomethingAsynchronous之后是安全的

我会这样做:

//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
}

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

如果使用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);
});

使用回调函数:

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