在我的 Angular 应用程序中,这个异步\await 代码究竟是如何工作的?为什么排序的方法没有显式返回 Promise?



我不太喜欢RxJS,我发现在理解我正在工作的Angular项目中检索的这段代码时遇到了一些问题。

首先进入一个组件TypeScript代码我有这样的方法:

async post(): Promise<void> {
this.submitted.next(true);
try {
await this.setAddress();
this.activeModal.close();
} catch (e) {
console.error('Storage upload error', e);
this.submitted.next(false);
}
}

正如您所看到的,这个方法有async前缀,因为在try块中包含以下两行:

await this.setAddress();
this.activeModal.close();

根据我的理解(如果我做了错误的断言,请纠正我(,基本上是在这个.setAddress((前面的await,它的意思是:等待这个方法调用结束,当它完成时执行以下操作(在这种情况下关闭模式窗口(。

据我所知,它重新保存了处理Promise解析的then((方法。它正确与否?

所以我的疑问是:我的setAddress((方法是否返回Promise?在我的特定情况下,setAddress((方法用于调用一个在数据库中保存一些数据的服务方法,并具有以下代码:

async setAddress(): Promise<void> {
try {
const c: Address = {
companyName:this.addressFormGroup.get('companyName').value,
street: this.addressFormGroup.get('street').value,
city: this.addressFormGroup.get('city').value,
zipCode: this.addressFormGroup.get('zipCode').value,
notes: this.addressFormGroup.get('notes').value,
};
//save/update record
await this.userService.setUserAdresss(this.currentUserUID,this.addressType,c);
this.success = true;
if (!this.isEditMode) {
this.addressFormGroup.reset();
}
} catch (e) {
console.error(e);
} finally {
this.submitted.next(false);
}
}

在这里,我对它的工作原理有很多疑问。。。确定方法签名:

async setAddress(): Promise<void> {

似乎返回了承诺(为什么?这意味着什么?(。但它在哪里有效地返回了一个承诺?在这个方法的代码中,我找不到它在任何地方都返回Promise。在我看来,它没有返回任何内容,因为它不包含return语句!!!

我唯一的解释是以下(但这是我的想法,可能完全错误(:如果它没有显式返回任何内容,那么它将有一个Promise作为方法返回类型。因此,这意味着在方法执行结束时,TypeScript自动返回一个";"空";承诺的意思很简单:;方法执行完成";。

我绝对不确定,这是我能给这个代码的唯一解释。

它是如何工作的?

您的假设是正确的。

用async关键字声明的函数将返回一个Promise,该Promise在函数完成执行时完成。

await关键字相当于使用带有剩余代码行的then方法作为回调函数。

在等待中使用try/catch/finally相当于在promise中使用catch/finaly方法。

这是用promise而不是async/await:编写的代码

post(): Promise<void> {
this.submitted.next(true);
return this.setAddress()
.then(() => this.activeModal.close())
.catch((e) => {
console.error('Storage upload error', e);
this.submitted.next(false);
});
}
setAddress(): Promise<void> {
const c: Address = {
companyName:this.addressFormGroup.get('companyName').value,
street: this.addressFormGroup.get('street').value,
city: this.addressFormGroup.get('city').value,
zipCode: this.addressFormGroup.get('zipCode').value,
notes: this.addressFormGroup.get('notes').value,
};
//save/update record
return this.userService.setUserAdresss(this.currentUserUID,this.addressType,c)
.then(() => {
this.success = true;
if (!this.isEditMode) {
this.addressFormGroup.reset();
}
})
.catch((e) => console.error(e))
.finally(() => this.submitted.next(false));;
}

最新更新