Angular 5 Await Not Waiting

大憨熊 提交于 2019-12-11 18:17:48

问题


When I run the code below, the checkCard function runs before the getTimecard function is finished.

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

Why Isn't checkOverlap waiting for getTimecard to return its data?


回答1:


To make a function awaitable the function needs to return a Promise.

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


来源:https://stackoverflow.com/questions/51860844/angular-5-await-not-waiting

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!