如何在 Angular 2/4 Typescript 中按顺序运行函数

Wei*_*inn 5 asynchronous typescript angular

我在尝试在我的 Angular 2/4 项目中按顺序运行函数时遇到问题。

我有retrieveData()从数据服务中检索数据并将它们分配到我声明的数组中的函数。

然后我有displayData()使用存储在数组中的数据并将它们显示在图表中的函数。

当我尝试运行它们时,例如:

function(){
  this.retrieveData();
  this.displayData();
}
Run Code Online (Sandbox Code Playgroud)

displayData()函数先运行retrieveData()主要是因为函数中的数据服务retrieveData()。因此无法正确显示图形。

我发现可以按顺序运行函数的方法之一是async.waterfallasync库中,但我无法将库导入到我的项目中,控制台日志显示: Uncaught Error: Unexpected value 'waterfall' imported by the module 'AppModule'. Please add a @NgModule annotation.

我不想使用 Promises 和 Observables,因为它们要求初始函数具有某种返回值以传递给下一个函数。我在某种程度上设法使用setTimeOut()函数来实现它,但我真的怀疑该方法的可靠性和稳健性。

那么,async在 Angular 2/4 中使用 有什么帮助,或者有什么方法可以让函数在没有任何返回承诺的情况下等待?

更新

很抱歉给大家带来的困惑和不便。我正在发布并要求一个过度简化的版本。这是我的代码中更完整的部分。我是一个 Angular 和 Typescript 菜鸟,在 Async 编程技术方面更是菜鸟。

下面是我在retrieveAllData()方法中实现的承诺。它在编译时或运行时都不会出现任何错误。但是当函数仍然异步运行时,即refreshAllCharts()仍然在retrieveAllData(). 我对承诺的实现有什么缺陷吗?

import { Component, OnInit, AfterContentInit } from '@angular/core';
import { DataService } from '../data.service';
import {BaseChartDirective} from 'ng2-charts/ng2-charts';
import {IMyDpOptions,IMyDateModel} from 'mydatepicker';

//import {MomentTimezoneModule} from 'angular-moment-timezone';
import * as moment from 'moment-timezone';

// import async from 'async-waterfall';

@Component({
  templateUrl: 'chartjs.component.html'
})
export class ChartJSComponent {

  tempArr = []; //array to store temperature values for the chart
  timeTempArr = []; //array to store timestamps for the chart label

  device = "1CB001"; //a parameter used for the data service method to query the database

  dateSelected; //variable to store the date chosen from the datepicker on the html side of the component

  constructor(private dataService: DataService){
  }

  ngOnInit(){
  }

//function to retrieve temperature values and assign them into "tempArr" array
  retrieveTempDataAssign(){
    var _arr = new Array();

    this.dataService.getData(this.device, this.dateSelected).subscribe(response => {

      console.log("Response: " + JSON.stringify(response));
      for(var item of response){
        _arr.push(item.Temperature);
      }

      this.tempArr = _arr;
      console.log("Array assigned Temp: " + this.tempArr);
    });

    this.retrieveTempTimeDataAssign();

  }

//function to retrieve time values and assign the date and time objects into "timeTempArr" array
  retrieveTempTimeDataAssign(){

    var _arr = new Array();

    this.dataService.getData(this.device, this.dateSelected).subscribe(response => {

      for(var item of response){
        // var value = "'" + item.Date + "'";
        // _arr.push(value);

        var value = item.Date;
        var time = moment.tz(value, "Asia/singapore");
        _arr.push(time);
      }
      this.timeTempArr = _arr;
      console.log("Array assigned Time: " + this.timeTempArr);
    });
  }

//function to refresh the whole of Temperature chart
  refreshTempChart(){
    this.showTempData();
    setTimeout(() => this.showTempLabels(), 500);
  }

//function to assign the "tempArr" array into the dataset for the temperature chart
  showTempData(){
    console.log("To display: " + this.tempArr);
    this.datasetsTemp = [{
      label: "Values",
      data: this.tempArr
    }];
  }

//function to assign the "timeTempArr" array into the labels for the temperature chart
  showTempLabels(){
    console.log("To label: " + this.timeTempArr);
    this.labels = this.timeTempArr;
  }

//date picker format
  private myDatePickerOptions: IMyDpOptions = {
        dateFormat: 'yyyy-mm-dd',    
  };

//change event listener on the datepicker
  onDateChanged(event: IMyDateModel){

    this.dateSelected= event.formatted;
    console.log("Selected Date: " + this.dateSelected);

//**The implementation part**
    this.retrieveAllData().then(()=>{
      this.refreshAllCharts();
    })

  }

//to run all functions to retrieve respective data
  retrieveAllData(){
    return new Promise((resolve, reject) => {
      this.retrieveTempDataAssign(); //assign the retrieved values into the array first

      return true;
    });
  }

//to run all functions to update all the charts
  refreshAllCharts(){
    this.refreshTempChart();
  }

//objects used by the chart to display data
  private datasetsTemp = [
    {
      label: "Values",
      data: []
    }
  ];

  private labels = [];

  private options = {
    scales: {
      xAxes: [{
          display: true,
          type: "time",
          time: {
              unit: "hour",
              tooltipFormat: 'YYYY-MM-DD hh:mm A'
          },
          scaleLabel: {
              display: true,
              labelString: 'Time'
          }
      },],
      yAxes: [{
        ticks: {
          beginAtZero: false
        }
      }]
    }
  };
}
Run Code Online (Sandbox Code Playgroud)

kuc*_*raf 3

使用 Promise 时,您不必返回任何值来传递给下一个函数。如果你想保持函数签名不变(即retrieveData()displayData()接受任何参数并返回 void),请考虑使用这样的 Promise:

private dataStorage: string = null;
private retrieveDataResolver;

  displayData(): void {
    // your display code goes here
    console.log("2. DISPLAYING DATA", this.dataStorage);
  }
  retrieveData(): void {
    // your async retrieval data logic goes here
    console.log("1. GETTING DATA FROM SERVER");
    setTimeout(() => { // <--- Change it - your service data retrieval
      this.dataStorage = '++DATA++';
      this.retrieveDataResolver(); // <--- This must be called as soon as the data are ready to be displayed
    }, 1000);
  }

  retrieveDataPromise(): Promise<any> {
    return new Promise((resolve) => {
      this.retrieveDataResolver = resolve;
      this.retrieveData();
    })
  }
  retrieveAndThenDisplay() {
    this.retrieveDataPromise().then(() => {this.displayData()});
  }
Run Code Online (Sandbox Code Playgroud)

我建议使用 Promise 包装器作为强大的链接结构来序列化异步操作