如何做才能让你的JavaScript code执行*为了* [英] How do you make javascript code execute *in order*

查看:137
本文介绍了如何做才能让你的JavaScript code执行*为了*的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好了,所以我AP preciate JavaScript是不是C#或PHP,但我继续回来在Javascript的问题 - 不能与JS本身,而是我用吧

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.

我有一个函数:

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的强烈愿望领先于code跳,装载机永远不会出现,因为hideLoader功能后直接运行。

Thing is, owing to Javascript's burning desire to jump ahead in the code, the loader never appears because the 'hideLoader' function runs straight after.

我该如何解决这个问题?或者换句话说,我怎样才能使订单的JavaScript函数执行我把它写在页面上...

How can I fix this? Or in other words, how can I make a javascript function execute in the order I write it on the page...

推荐答案

出现问题的原因AJAX是其性质asynchronus。这意味着 updateStatus()调用,以确实执行,但返回立刻和JS跨preTER达到 hideLoader()之前的任何数据从AJAX请求retreived。

The problem occurs because AJAX is in its nature asynchronus. This means that the updateStatus() calls are indeed executed in order but returns immediatly and the JS interpreter reaches hideLoader() before any data is retreived from the AJAX requests.

您应该执行 hideLoader()在哪里Ajax调用完成的事件。

You should perform the hideLoader() on an event where the AJAX calls are finished.

这篇关于如何做才能让你的JavaScript code执行*为了*的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆