skip to Main Content

I’m having trouble understanding how to use async/await in this scenario. I have a function GetAdditionalProducts() that calls a service and returns a result. I call that function elsewhere where I need access to that result but it executes that code before the response is available. How can I use async/await to wait for the reponse before moving on?

  onSearch() {
    this.GetAdditionalProducts();
    //other stuff that requires the response from above function
  }   

  GetAdditionalProducts() {
    this.proposalService.getProductList(this.filter).subscribe(response => {
      this.additionalProducts = response.productList;
    });
  }

2

Answers


  1. I see you are using "subscribe", which imply RxJS. You could use the lastValueFrom function to convert your observable to a promise.

    import { lastValueFrom } from 'rxjs'
    
    async GetAdditionalProducts() {
        return lastValueFrom(this.proposalService.getProductList(this.filter))
    }
    

    If you want to make your own implementation, you could wrap your this.proposalService.getProductList(this.filter) call into a promise and then resolve the promise in your "subscribe" callback.

    Whatever you pass to the Promise’s resolve will be the return value of your promise, and accessible when using await on the function.

     async GetAdditionalProducts() {
        return new Promise(resolve => {
          this.proposalService.getProductList(this.filter).subscribe(response => {
            resolve(response.productList);
          });
        })
      }
    
    

    And then, you can call the GetAdditionalProducts and awaiting the response.

    async onSearch() {
      this.additionalProducts = await this.GetAdditionalProducts();
    }
    

    Edit:
    The new standard for transforming an observable to a promise seams to be lastValueFrom. I’ve edited my answer. Thank you Bojan for pointing it out.

    Login or Signup to reply.
  2. When you think of observables, consider it normal to place the additional actions inside the subscribe. The code in the subscribe is asynchronous (waits for the API to complete) the code below the subscribe is synchronous (does not wait for completion) so you need to move the code inside to chain the actions.

    When working with observables converting to promise and back seems a bit extra effort and should be done only when there is an absolute need to.

      onSearch() {
        this.GetAdditionalProducts();
      }   
    
      GetAdditionalProducts() {
        this.proposalService.getProductList(this.filter).subscribe(response => {
          this.additionalProducts = response.productList;
          this.additionalActions();
        });
      }
    
      additionalActions() {
        //other stuff that requires the response from above function
      }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search