javascript - 控制程序的流程
我有 start(),并且只想在 getCityInformation() 完全执行完之后才继续我的代码。控制台应该输出 ('getCityInformation' => 'done' => 'finished')。我如何控制这个流程?
async start() {
await this.getCityInformation().then(() => console.log('done'));
console.log('finished');
}
async getCityInformation() {
this.apiService.getProductsByCategory(this.city.CategoryID)
.subscribe((data: Product[]) => {
console.log('getCityInformation')
this.products = data;
},
(err) => console.log(err),
() => this.loadActivities()
);
}
答案#1
你当前的 done、finished 和 getCityInformation 的顺序是有道理的,因为在异步的 getCityInformation() 中,你实际上是立即返回的(例如,并没有 await 某些东西)。所以链条是这样的:
start()调用getCityInformation()getCityInformation()订阅一个可观察对象并返回getCityInformation()现在完成了,start()会打印donestart()打印finishedgetCityInformation()中的回调会收到更新并打印getCityInformation
要解决这个问题,你需要在 getCityInformation() 中等待,直到可观察对象准备好为止。例如,你可以返回一个 Promise,当你拥有所有需要的数据时该 Promise 就会被解决。
答案#2
你需要返回 promise 来等待
getCityInformation函数的结果
async start() {
await this.getCityInformation().then(() => console.log('done'));
console.log('finished');
}
async getCityInformation() {
return new Promise((resolve, reject) => {
this.apiService.getProductsByCategory(this.city.CategoryID)
.subscribe((data: Product[]) => {
console.log('getCityInformation')
this.products = data;
resolve(data)
},
(err) => reject(err) ,
() => this.loadActivities()
);
})
}
