代码在数据到达之前进入功能 - 如何让它在继续之前等待所有数据?

Code enters function before data arrives - How to make it wait for all data before continuing?

我订阅了可观察对象,然后将数据放入数组中(array_item)。在第二个 foreach() 中,我遍历数组以获取我的数据,但它从未执行过,因为数组仍然是空的。我的意思是当我还没有收到我所有的数据时,执行转移到了这个 foreach() 上。在继续第二个 foreach() 和操作数组 (array_item) 项之前,我怎样才能让它等到所有数据都收到并在数组中。

names: any[] = [];
array_item: any[] = [];
drawtimeline(nom_cal, _hitoService, idcalbuscador) {
  this.names.forEach((ev) => {
    groups.add([{id: ev._id, content: ev.nom_calendario, cal_id: ev._id}]);
    var g = ev._id;


    for (var i = 0; i < this.names.length; i++) {
      this._hitoService.getHitos(this.names[i]._id)
          .subscribe(hito1 => {
            this.hito1 = hito1
            this.array_item.push(hito1);
          });
    }

    console.log("before 2nd foreac()");
    for (var j = 1; j < this.array_item.length; j++) {
      console.log("inside 2nd foreac()");
      this.array_item[j].forEach((item) => {
        console.log("i =  " + i + " id_item: " + this.calendarObject._id + " j =" + j);
        items.add([{
          id: i,
          group: g,
          start: item.start_datetime,
          end: item.end_datetime,
          style: itemStyle(item.design),
          className: "pepe"
        }]);
        console.log("i =  " + i + "id_item: " + this.calendarObject._id);
      });
    }

  });
}

任何依赖于异步进程的代码只能在异步进程完成后调用。要等待所有响应,您可以使用 forkJoin:RxJS Observable.forkJoin

import {Observable} from 'rxjs';

const requests = Observable.forkJoin(this.names.map(name => this._hitoService.getHitos(name._id)));
requests.subscribe(responses => { <do stuff with responses here> });

responses 将是每次调用 _hitoService.getHitos

的响应数组

import {Observable} from 'rxjs/Observable';

names: any[] = [];
array_item: any[] = [];
drawtimeline(nom_cal, _hitoService, idcalbuscador) {
  this.names.forEach((ev) => {
    groups.add([{
      id: ev._id,
      content: ev.nom_calendario,
      cal_id: ev._id
    }]);
    var g = ev._id;

    Observable.forkJoin(this.names.map(v => {

      return this._hitoService.getHitos(v._id)
        .map(hito1 => {
          this.hito1 = hito1;
          this.array_item.push(hito1);
        })
    })).subscribe(res => {

      console.log("before 2nd foreac()");
      for (var j = 1; j < this.array_item.length; j++) {
        console.log("inside 2nd foreac()");
        this.array_item[j].forEach((item) => {
          console.log("i =  " + i + " id_item: " + this.calendarObject._id + " j =" + j);
          items.add([{
            id: i,
            group: g,
            start: item.start_datetime,
            end: item.end_datetime,
            style: itemStyle(item.design),
            className: "pepe"
          }]);
          console.log("i =  " + i + "id_item: " + this.calendarObject._id);
        });
      }

    });
  })
}