简体   繁体   中英

How exactly works this async\await code in my Angular application? Why the colled method doesn't explicitly return a Promise?

I am not so into RxJS and I am finding some problems to understand this piece of code retrieved into an Angular project on which I am working.

First of all into a component TypeScript code I have this method:

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

As you can see this method have async prefix because into the try block it contains these 2 rows:

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

from what I have understand (please correct me if I am doing wrong assertion) basically the await in front of this.setAddress() it means: await that this method call end, when it is completed executed the following operation (that in this case close a modal window).

From what I have understand it replave the then() method handling a Promise resolution. Is it correct or not?

So my doubt is: have my setAddress() method return a Promise? In my specific case setAddress() method is used to call a service method saving some data on the database and have this code:

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

And here I have a lot of doubts on how it works...ok the method signature:

async setAddress(): Promise<void> {

seems to return a Promise (why? what it means?). But where is it effectivelly returning a Promise? In the code of this method I can't find that it is returning a Promise nowhere. It seems to me that it is returning nothing because it is not containing the return statement !!!

My only interpretation is the following one (but it is my idea and probably totally wrong): also if it is not explicitly returning nothing it have a Promise as method returned type. So it means that at the end of the method execution TypeScript automatically return an "empty" Promise that simply means: "method execution completed".

I am absolutly not sure, this is the only explaination that I can give to this code.

How it wxactly works?

Your assumptions are correct.

A function declared with the async keyword will return a Promise that is completed when the function has finished its execution.

The await keyword is equivalent to using the then method with the remaining lines of codes as the callback function.

Using try/catch/finally arround an await is equivalent to using the catch/finally method on the promise.

This is your code written with promises instead of 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));;
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM