Instead of 'converting' observables to promises (assuming reference to toPromise()
), the approach here is to wrap subscriptions in promises and use Promise.all()
for concurrent await.
constructor(private http: HttpClient) {}
async waitForResponses() {
const obs1 = this.http.get('api1');
const obs2 = this.http.get('api2');
const obs3 = this.http.get('api3');
const promise1 = new Promise((resolve) =>
obs1.subscribe((result) => resolve(result))
);
const promise2 = new Promise((resolve) =>
obs2.subscribe((result) => resolve(result))
);
const promise3 = new Promise((resolve) =>
obs3.subscribe((result) => resolve(result))
);
const [result1, result2, result3] = await Promise.all<any>([promise1, promise2, promise3]);
console.log(result1);
console.log(result2);
console.log(result3);
}
This method allows awaiting all API calls concurrently with flexibility on the order. Results are returned as an array at their respective index correlating with the promise. This likely meets your intended outcome.
Error handling:
const promise1 = new Promise((resolve, reject) =>
obs1.subscribe({
next: (result) => resolve(result),
error: (err) => reject(err),
})
).catch((err) => console.log(err));