Detecting completion of multiple async javascript $ .ajax calls

I have a javascript function that goes into a loop and throws an ajax asynchronous call for each loop. I need to know when ALL ajax calls returned and were processed, because I want to update the interface at this point.

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 to invoke the UI update function when the last async async call eventually returned from the server?

Thank.

+3
source share
2 answers

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

, "" , "", "", , "" . , "total", . ( ) ajax , , , , .

+7
+2

All Articles