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
I see you are using "subscribe", which imply RxJS. You could use the
lastValueFrom
function to convert your observable to a promise.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 usingawait
on the function.And then, you can call the
GetAdditionalProducts
and awaiting the response.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.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.