[英]make javascript loading functions to execute one after the other
I have a function where in I execute 2 functions. 我有一个函数,我执行两个函数。 When I view it in the browser, I get 2 loading symbols which i use for showing the loading of data.
当我在浏览器中查看它时,我得到2个加载符号,用于显示数据的加载。
I wanted to know if there is a way to execute each function, one after the other, since I can avoid the 2 loading symbols. 我想知道是否有一种方法可以一个接一个地执行,因为我可以避免两个加载符号。 I don't want to call the second function inside the first function as a solution.
我不想在第一个函数内调用第二个函数作为解决方案。
The code is as shown below: 代码如下所示:
function ABCD() {
function x();
function y();
}
I want function x() to complete its execution and then start with function y() 我希望函数x()完成其执行,然后从函数y()开始
Assuming your functions return jQuery promises, you can do something like this: 假设您的函数返回jQuery Promise,您可以执行以下操作:
function ABCD() {
// return the sequential promises
return x().then(y); // or return x().done(y); if you want a result after first one only
}
then outside you can wait for both with a call like this: 然后在外面,您可以通过这样的呼叫等待两者:
ABCD().done(function(){
alert("both complete");
});
if x
and y
make an ajax call just return that, as it is already a promise: 如果
x
和y
进行ajax调用,则只需返回它,因为它已经是一个承诺:
eg 例如
function x(){
return $.ajax(...);
}
function y(){
return $.ajax(...);
}
Working Example JSFiddle: http://jsfiddle.net/TrueBlueAussie/9e5rx2bx/2/ JSFiddle工作示例: http : //jsfiddle.net/TrueBlueAussie/9e5rx2bx/2/
Note: the example uses Deferred
and setTimeout
to simulate the ajax loads. 注意:该示例使用
Deferred
和setTimeout
模拟ajax负载。 Have the console open to see the log activity. 打开控制台以查看日志活动。
The older (non-promise way) would be using callbacks, however the exact implementation depends on your actual current code (which is not shown): 较旧的(非承诺方式)将使用回调,但是确切的实现取决于您当前的实际代码(未显示):
This is a preferred way of solving this type of issue since jQuery 1.5. 从jQuery 1.5开始,这是解决此类问题的首选方法。
Here is a vanilla js option (note the callback function is x()
has been made optional (ie x()
executes just fine without a callback). DEMO 这里是一个香草js的选项操作(注意回调函数是
x()
已经取得了可选的(即x()
没有回调执行就好了)。 DEMO
function y() {
//execute code
}
function x(callback) {
//execute code
if (typeof(callback) === 'function') {
callback();
}
}
function ABCD() {
x(y());
}
ABCD();
Alternate version with @TrueBlueAussie's suggestion: DEMO2 @TrueBlueAussie的建议的替代版本: DEMO2
function x(callback) {
//execute code
if(callback) callback()
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.