当我运行下面的代码时,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返回其数据?
答案 0 :(得分:2)
要使一个函数可以等待,该函数需要返回一个Promise。
loadTimecards() {
return new Promise(resolve => {
this.sending = true;
this._service.getTimecard().subscribe(data => {
this.sending = false;
this.timecards = data;
resolve();
});
});
}