数组填充后如何调用函数

时间:2020-04-30 16:46:22

标签: javascript chart.js

我有一个使用chart.js构建图表的函数,但是有时该函数在我获取数据的前一个函数尚未完成时运行,因此图表中断了,我该如何调用函数?有我需要的所有数据吗? 我想使用与setTimeout不同的方法,因为我已经使用过它,但有时它仍然会失败,所以我不想一直增加超时数

    if (regionData !== undefined) {
    that.hasData = true;
    Object.entries(regionData).forEach(e => {
      let obj = {};
      let value = 0;
      let regionD = all_regions.map(function (e) { return e.id; }).indexOf(e[0]);
      obj["regionDescription"] = all_regions[regionD].data.d;
      obj["region"] = e[0];
      if (e[1] !== undefined && e[1]["month"] !== undefined) {
        value = e[1]["month"][e[1]["month"].length - 1];
      }
      obj["regio"] = value;
      regionS.push(obj);
    });
    that.buildChart(regionS, lastMonth);
  }

那是我调用图表函数的地方

1 个答案:

答案 0 :(得分:1)

我看不到您的其余代码,但是根据您的描述,有一个简单的逻辑解决方案。

问题在于buildChart函数在getChartData函数之前运行。 解。在getChartData函数之后调用buildChart函数。 伪代码示例,

const getChartData = () => {
    return new Promise((resolve) => {
        Run your HTTP request and retrieve your data
        resolve(chart data ready to be used)
    });
}
const buildChart = () => {
    // do your chart building here
}
//then you run the functions in sequence.
getChartData().then(buildChart);