how to wait until Array is filled (asynchronous)

后端 未结 2 809
温柔的废话
温柔的废话 2021-01-05 16:30

I have an array which is filled asynchronous and contains 28 items. I want to wait until the array is filled with all items.

function checkIfFinished(){
             


        
2条回答
  •  轮回少年
    2021-01-05 16:50

    If you're using jQuery 1.5+, this sounds like a perfect opportunity to use deferred objects and promises in your code. I'm assuming that you're using AJAX calls to populate your array.

    In a nutshell, something like this should work for you:

    $(function() {
    
        var $ajaxcalls = [],
            myArray = [];
    
        // set up all the ajax calls that will populate my array
        for(var i=0; i < 28; i++) {
            $ajaxcalls[i] = $.ajax({
                url : 'http://your.domain.com/blah',
                data : i
            }).success(function(m) {
                myArray.push(m);
            });
        }
    
        // this will setup the promise --- 
        // what will run when all 28 AJAX calls complete?
        $.when.apply(null, $ajaxcalls).then(function() {
            returnResults();
        });
    
    });
    

    I've written about this some time back as well. I really think it's a nifty feature / concept that can be really powerful when used correctly. Javascript timers and schedules should work as well, but they can be unwieldy and may result in a bit of wait time before the actual completing logic fires.

提交回复
热议问题