Reputation: 1872
I have a set of functions to run, in sequence, but the first one has an asynchronous sub-function. I want the second highest-level function to run only after the async function completes. Any idea how I do this?
File A:
one();
two(); // I don't want this to run until after one()'s $.ajax success callback
function one() {
doSomethingElse();
$.ajax(url, {data: data}, function(){
// do two();
});
}
Upvotes: 0
Views: 5016
Reputation: 5625
function one() {
doSomethingElse();
$.ajax(url, {data: data}, function(){
// do two();
two();
});
}
function two(){
alert("here");
}
Upvotes: 0
Reputation: 298166
Change your function to return the AJAX object:
function one() {
doSomethingElse();
return $.ajax({
url: url,
data: data
});
}
And now you do:
one().done(function() {
two();
});
It's a little cleaner than putting two()
directly into the callback.
Upvotes: 1
Reputation: 14225
Promises are the best option for your purposes
jQuery deferreds and promises - .then() vs .done()
Upvotes: 0