【发布时间】:2021-05-16 04:02:48
【问题描述】:
我不太喜欢 Angular 和异步编程,我有以下疑问。
进入服务类我有这个异步方法:
async aestheticEvaluationExist(patientUID: string) {
console.log("patientUID: ", patientUID);
//return this.firestore.collection('aestetic-evaluation').doc(patientUID).get();
//const docRef = (await this.firestore.collection('aestetic-evaluation').doc(patientUID).);
const exists: boolean = (await this.firestore.collection('aesthetic-evaluation').doc(patientUID).get().toPromise()).exists;
console.log("aesteticEvaluationExist() exists: ", exists);
return exists;
}
然后进入我的组件类我有这个方法调用之前的服务方法::
let isUpdate = true;
(await this.patientService.aestheticEvaluationExist(this.patientUID)
.then(res => {
console.log("RES: ", res);
isUpdate = res;
}));
console.log("isUpdate: ", isUpdate);
如您所见,它在方法调用之前有 awayt 关键字。
它似乎工作正常(输出是正确的)事实上进入 then() 我的 res 是假的,当我通过最后一个 console.log() 行打印它时它打印 false,表示原来的真值被正确覆盖了。
我正在询问该 async 服务方法定义是否在方法调用上带有 await 关键字,以确保我的最后一个 console.log() 行在我的方法完成之后执行。
我的理解正确吗?或者为了确保正确的结果,我必须在 then() 中执行最后一个操作?
【问题讨论】:
-
没有理由将
await和then混在同一个地方。它工作,但它是不必要的复杂。let isUpdate = await this.patientService.aestheticEvaluationExist(this.patientUID)也是如此,它更短,更易于阅读、理解和调试。
标签: angular typescript async-await angular-promise