Yes, the method you've written ensures that getAPICall() completes before putAPICall() is called, if and only if the condition is true.
Let's break it down:
public async myMethod() {
if (this.condition) {
this.myData = await this.myService.getAPICall();
}
this.myService.putAPICall().subscribe({});
}
Key Points:
-
await this.myService.getAPICall():
- This line pauses execution of the rest of the function until the
getAPICall() Promise resolves.
- So, if
this.condition is true, putAPICall() will not be called until after getAPICall() completes.
-
putAPICall().subscribe({}):
- This starts the HTTP request (assuming it's an Angular
HttpClient call).
- However, since this line is after the
await, it will execute only after the awaited Promise resolves.
-
If this.condition is false, then getAPICall() is not executed at all, and putAPICall() is called immediately.
Summary
✅ Yes, the code ensures that getAPICall() finishes before putAPICall() begins — but only when this.condition is true.
Optional Enhancement: Make putAPICall wait for completion too
If you want to ensure that putAPICall() also completes before continuing (e.g., if your method needs to wait for both calls to finish), you should also await it, but note that .subscribe() doesn't return a Promise by default. You would need to convert it or use toPromise() (deprecated in newer RxJS versions).
Example using lastValueFrom (recommended):
import { lastValueFrom } from 'rxjs';
public async myMethod() {
if (this.condition) {
this.myData = await this.myService.getAPICall().toPromise();
}
await lastValueFrom(this.myService.putAPICall());
}
This version waits for both API calls to complete (if needed).