How do you make javascript code execute *in order*

后端 未结 9 1184
别那么骄傲
别那么骄傲 2020-11-30 05:49

Okay, so I appreciate that Javascript is not C# or PHP, but I keep coming back to an issue in Javascript - not with JS itself but my use of it.

I have a function:

9条回答
  •  暖寄归人
    2020-11-30 06:34

    We have something similar in one of our projects, and we solved it by using a counter. If you increase the counter for each call to updateStatus and decrease it in the AJAX request's response function (depends on the AJAX JavaScript library you're using.)

    Once the counter reaches zero, all AJAX requests are completed and you can call hideLoader().

    Here's a sample:

    var loadCounter = 0;
    
    function updateStatuses(){
        updateStatus('cron1'); //performs an ajax request to get the status of something
        updateStatus('cron2');
        updateStatus('cron3');    
        updateStatus('cronEmail');
        updateStatus('cronHourly');
        updateStatus('cronDaily');
    }
    
    function updateStatus(what) {
        loadCounter++;
    
        //perform your AJAX call and set the response method to updateStatusCompleted()
    }
    
    function updateStatusCompleted() {
        loadCounter--;
        if (loadCounter <= 0)
            hideLoader(); //hide the 'loader.gif' in the UI
    }
    

提交回复
热议问题