Angular 5等待不等待

时间:2018-08-15 14:38:10

标签: javascript typescript async-await angular5

当我运行下面的代码时,checkCard函数在getTimecard函数完成之前运行。

getTimecard() {
  this._service.getTimecard().subscribe(
  data => {
    this.sending = true;
    this.timecards = data;
  },
  err => {
    this.sending = false;
    console.error(err);
  },
  () => {
    this.sending = false;
  }
);
}

checkCards() {
  console.log('timecards', this.timecards);
  //code dependent on timecard data
}

async onSubmit() {
  await this.getTimecard();
  this.checkCards(); 
}

为什么checkOverlap不等待getTimecard返回其数据?

1 个答案:

答案 0 :(得分:2)

要使一个函数可以等待,该函数需要返回一个Promise。

loadTimecards() {
   return new Promise(resolve => {
     this.sending = true;
     this._service.getTimecard().subscribe(data => {
       this.sending = false;
       this.timecards = data;
       resolve();
     });
  });
}