依次执行一项功能 [英] Executing one function after another

查看:157
本文介绍了依次执行一项功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所有这些函数都在主函数中,该主函数在jQuery异步AJAX成功事件之后被调用,并且每秒运行一次.这三个函数中的每个函数也都调用其中的特定函数.

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.

这是我拥有的基本javascript代码:

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()-使用jQuery .load()方法基于特定的AJAX数据加载HTML结构.

selectView() - Uses jQuery .load() method to load HTML structure based on specific AJAX data.

startWidgets()-通过将小部件放入HTML结构(基于ID和类)来初始化小部件.只在第一次运行.

startWidgets() - Initializes widgets by placing them into the HTML structure (based on IDs and classes). Only runs the first time.

popData()-根据AJAX数据将数据填充到所有其他小部件中.

popData() - Populates data to all other widgets based on AJAX data.

我尝试了$.when(selectView()).then(startWidgets).then(popData);

但是那没有用.我的问题是startWidgets通常在selectView之前运行,但是由于还没有HTML标记,因此它失败了.我需要它们按照特定的顺序运行,并且直到上一个完成后才能开始.

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.

推荐答案

我尚未对其进行测试,但类似的方法可能会对您有所帮助;)

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();

这篇关于依次执行一项功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆