首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何让javascript代码按顺序执行*?

如何让javascript代码按顺序执行*?
EN

Stack Overflow用户
提问于 2010-04-14 21:18:48
回答 6查看 32.3K关注 0票数 22

好吧,我很欣赏Javascript不是C#或PHP,但我总是回到Javascript的一个问题上--不是JS本身,而是我对它的使用。

我有一个函数:

function updateStatuses(){

showLoader() //show the 'loader.gif' in the UI

updateStatus('cron1'); //performs an ajax request to get the status of something
updateStatus('cron2');
updateStatus('cron3');
updateStatus('cronEmail');
updateStatus('cronHourly');
updateStatus('cronDaily');

hideLoader(); //hide the 'loader.gif' in the UI

}

问题是,由于Javascript在代码中跃进的强烈愿望,加载器永远不会出现,因为'hideLoader‘函数紧随其后运行。

我该如何解决这个问题呢?或者换句话说,我如何才能让javascript函数按照我在页面上编写的顺序执行……

EN

回答 6

Stack Overflow用户

发布于 2010-04-14 21:22:27

出现这个问题是因为AJAX本质上是异步的。这意味着updateStatus()调用确实是按顺序执行的,但会立即返回,并且JS解释器在从AJAX请求检索任何数据之前到达hideLoader()

您应该在AJAX调用完成的事件上执行hideLoader()

票数 16
EN

Stack Overflow用户

发布于 2011-07-14 20:35:42

我认为你所需要做的就是在你的代码中包含以下内容:

async: false,

因此,您的Ajax调用将如下所示:

jQuery.ajax({
            type: "GET",
            url: "something.html for example",
            dataType: "html",
            async: false,
            context: document.body,
            success: function(response){

                //do stuff here

            },
            error: function() {
                alert("Sorry, The requested property could not be found.");
            }  
        });

显然,需要对XMLJSON等进行一些更改,但async: false,是这里的主要内容,它告诉JS引擎等待成功的调用返回(或失败),然后继续执行。记住,这有一个缺点,那就是在ajax返回之前,整个页面都会变得没有响应!通常在毫秒内,这不是一个大的交易,但可能需要更长的时间。

希望这是正确的答案,它对您有帮助:)

票数 10
EN

Stack Overflow用户

发布于 2010-04-14 21:34:59

我们在我们的一个项目中有类似的东西,我们通过使用计数器解决了它。如果您在AJAX请求的响应函数中为每个updateStatus调用增加计数器并减少它(取决于您正在使用的AJAX JavaScript库)。

一旦计数器达到零,所有AJAX请求都完成,您就可以调用hideLoader()了。

下面是一个示例:

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
}
票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/2637626

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档