Reputation: 137
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.
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()
Upvotes: 0
Views: 78
Reputation: 93631
Assuming your functions return jQuery promises, you can do something like this:
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:
e.g.
function x(){
return $.ajax(...);
}
function y(){
return $.ajax(...);
}
Working Example JSFiddle: http://jsfiddle.net/TrueBlueAussie/9e5rx2bx/2/
Note: the example uses Deferred
and setTimeout
to simulate the ajax loads. 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.
Upvotes: 3
Reputation: 7568
Here is a vanilla js option (note the callback function is x()
has been made optional (i.e. x()
executes just fine without a callback). 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
function x(callback) {
//execute code
if(callback) callback()
}
Upvotes: 1