Executing one function after another

时光毁灭记忆、已成空白 提交于 2019-12-11 14:58:21

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!