检测多个异步javascript $ .ajax调用的完成情况

时间:2022-12-06 10:40:34

I have a javascript function that enters a loop and issues an asynchronous ajax call for each loop. I need to know when ALL the ajax calls have returned and been processed, because I want to update the UI at that point.

我有一个javascript函数进入循环并为每个循环发出异步ajax调用。我需要知道所有ajax调用何时返回并被处理,因为我想在那时更新UI。

The loop is as follows:

循环如下:

function sync_SyncLocalStorageToServer() {
    if (helper_IsAppOnline()) {
        $.log('sync_SyncLocalStorageToServer detects app is ONLINE');
        // Post each cached entry to the server - this is the main sync function
        for (var i = 0, len = localStorage.length; i < len; i++) {
            var lskey = localStorage.key(i);
            if (lskey.substr(0, 8) === 'response') {
                $.log('Sync found response with key=' + lskey);
                var postdata = localStorage.getItem(lskey); // Get the form data
                $.log('Calling server with ls response:' + postdata);
                var localkey = lskey;
                $.ajax({
                    type: "POST",
                    dataType: 'json',
                    url: "/Profile/PostForm",
                    data: { jsonpost: postdata },
                    success: function (data) {
                        if (data.rc == "success") {
                            localStorage.removeItem(data.localStorageKey); // Remove the relevant localStorage entry
                            $.log('ServerSuccess:' + data.message + ',removed localStorageKey=' + data.localStorageKey);
                        } else {
                            $.log('ServerUnhappy:' + data.message + ',did not remove localStorageKey=' + data.localStorageKey);
                        }
                    }
            , error: function (data) {
                $.log('ERR:' + data);
            }
                });
            }
        }
    }
    else {
        $.log('sync_SyncLocalStorageToServer detects app is OFFLINE');
    }
}

What is the easiest way for me to call my UI refresh function when the very last async ajax call has eventually returned from the server?

当最后一次异步ajax调用最终从服务器返回时,我最简单的方法是调用我的UI刷新功能?

Thanks.

谢谢。

2 个解决方案

#1


7  

Count how many times you execute an AJAX request, and then, count the number of times you have seen a call to the completed callback. Once the callback completed count equals the number of times you issued ajax calls, you know you are done.

计算执行AJAX请求的次数,然后计算您看到对完成的回调的调用次数。一旦回调完成计数等于你发出ajax调用的次数,你知道你已经完成了。

var total = arr.length;
var count = 0;
for(var i = 0; i < arr.length; i++){
     $.ajax({
        // other options
        complete: function(){
            count++;
            if(count == total){ 
                // all finished!
            }
        }
     });
}

Note that I use the 'complete' callback, not 'success', since if one of the requests fail 'success' will not be called, but 'complete' will. Also, I declared the expected amount in 'total' first, instead of counting up in this example. This just avoid the unlikely (though technically possible) scenario of having all of the pending ajax requests finish before you've posted all of them, and therefore having a matching count.

请注意,我使用'完整'回调,而不是'成功',因为如果其中一个请求失败'成功'将不会被调用,但'完成'将会被调用。此外,我首先在'总数'中声明预期金额,而不是在此示例中计算。这样就可以避免在发布所有挂起的ajax请求之前完成所有挂起的ajax请求的可能性(尽管技术上可行),因此具有匹配的计数。

#2


2  

The easiest would be to attach a handler to the jQuery.ajaxStop event. If you require more hooks than this, you can attach to some of the other global AJAX events as well.

最简单的方法是将处理程序附加到jQuery.ajaxStop事件。如果您需要比此更多的钩子,您也可以附加到其他一些全局AJAX事件。

#1


7  

Count how many times you execute an AJAX request, and then, count the number of times you have seen a call to the completed callback. Once the callback completed count equals the number of times you issued ajax calls, you know you are done.

计算执行AJAX请求的次数,然后计算您看到对完成的回调的调用次数。一旦回调完成计数等于你发出ajax调用的次数,你知道你已经完成了。

var total = arr.length;
var count = 0;
for(var i = 0; i < arr.length; i++){
     $.ajax({
        // other options
        complete: function(){
            count++;
            if(count == total){ 
                // all finished!
            }
        }
     });
}

Note that I use the 'complete' callback, not 'success', since if one of the requests fail 'success' will not be called, but 'complete' will. Also, I declared the expected amount in 'total' first, instead of counting up in this example. This just avoid the unlikely (though technically possible) scenario of having all of the pending ajax requests finish before you've posted all of them, and therefore having a matching count.

请注意,我使用'完整'回调,而不是'成功',因为如果其中一个请求失败'成功'将不会被调用,但'完成'将会被调用。此外,我首先在'总数'中声明预期金额,而不是在此示例中计算。这样就可以避免在发布所有挂起的ajax请求之前完成所有挂起的ajax请求的可能性(尽管技术上可行),因此具有匹配的计数。

#2


2  

The easiest would be to attach a handler to the jQuery.ajaxStop event. If you require more hooks than this, you can attach to some of the other global AJAX events as well.

最简单的方法是将处理程序附加到jQuery.ajaxStop事件。如果您需要比此更多的钩子,您也可以附加到其他一些全局AJAX事件。