问题
All of these functions are in the main function which is called after jQuery async AJAX success event and it runs every second. Each of the three functions call specific functions within them as well.
This is the basic javascript code I have:
function mainFunction() {
function selectView(){
// do stuff
}
function startWidgets(){
// do stuff
}
function popData(){
// do stuff
}
$.when(selectView()).then(startWidgets).then(popData);
}
function ajaxCall(){
ajaxRequest = $.ajax({
type: "GET",
url: "",
data: {},
async: true,
cache: false,
timeout:50000,
success: function(data){
mainFunction();
setTimeout(
ajaxCall, 5000
);
},
error: function() {
// error stuff
},
complete: function() {
// complete stuff
}
});
}
selectView()
- Uses jQuery .load() method to load HTML structure based on specific AJAX data.
startWidgets()
- Initializes widgets by placing them into the HTML structure (based on IDs and classes). Only runs the first time.
popData()
- Populates data to all other widgets based on AJAX data.
I tried $.when(selectView()).then(startWidgets).then(popData);
But that did not work. My problem is startWidgets usually runs before selectView, but since there's no HTML markup yet, it fails. I need them to run in that specific order and one doesn't start till previous one is done.
回答1:
You need to return the promise objects from selectView
, if you are not returning a promise from selectView
then when
will consider the object as resolved and execute the success handlers.
Also I think it is best to handle the callbacks using .done()
function mainFunction() {
function selectView(){
// do stuff
var xhr = $.ajax(....);
....
return xhr;
}
function startWidgets(){
// do stuff
}
function popData(){
// do stuff
}
$.when(selectView()).done(startWidgets).done(popData);
}
回答2:
I haven't tested it, but something like that might helps you ;)
selectView_done = false;
startWidgets_done = false;
function selectView() {
// do stuff
selectView_done = true;
return ...;
}
function startWidgets() {
// do stuff
startWidgets_done = true;
}
function popData() {
// do stuff
}
function control_selectView(){
if( selectView_done ){
startWidgets();
control_popData();
}
else setTimeout(function(){ control_selectView() }, 100);
}
function control_popData(){
if( startWidgets_done ) popData();
else setTimeout(function(){ control_popData() }, 100);
}
selectView();
control_selectView();
来源:https://stackoverflow.com/questions/19033456/executing-one-function-after-another