Wait for multiple http requests to finish before running a function in angular

Brenden Engelbrecht

I have multiple http posts that fetches JSON data from a MySQL database. I want a function to listen to all of them and run the next piece of code once all of them returned that data has been received.

I've tried multiple variations of async with await, but the function doesn't appear to wait for the HTTP post to finish.

I've got a risk service risk.service.ts to get the riskTable for instance:

getRiskTable(): Observable<Risk[]> {
    return this.http.get(`${this.baseUrl}/getRiskTable`).pipe(
      map((res) => {
        this.riskTable = res['data'];
        return this.riskTable;
      }),
      catchError(this.handleError));
  }

On my Dashboard I call this code:

getRiskTable():any {
    return this.riskService.getRiskTable().subscribe(
      (res: []) => {
        this.riskTable = res; // the value is correctly captured here
        return true;
      },
      (err) => {
        this.error = err;
      }
    );
  }

And then an async function that runs multiple of these functions, in theory it's suppose to wait until all the functions complete and then log the value. But for some reason the global variable this.riskTable is undefined in this function.

async getAllData(){
    let riskTable = await this.getRiskTable();
    let risks = await this.getAllRisks();

    console.log(riskTable); //This returns stuff
    console.log(risks);
    console.log(this.riskTable); //This returns undefined even though it was set in getRiskTable
  }

Please any pointers - I am very new to angular and the complexity of this has me completely stumped. 2 Days and 100x variations to get this to work I am slowly losing my bananas!

Igor

First off the async/await keywords are for use with promises, not Observables. So you can convert an observable to a promise using toPromise() or you can use rxjs ForkJoin. You also need to change the methods to return either an observable or return a promise, you can't do much with Subscription which is what subscribe returns when you call it and that is what you are passing now from getRiskTable.

One other issue is that you are not taking advantage of the type system, do not use any everywhere because these errors could have been caught at transpile time and now you have to guess why it's failing at run time which is more difficult.

import { forkJoin } from 'rxjs';
import { shareReplay } from 'rxjs/operators';

getRiskTable() : Observable<Risk[]> {
  const tableObservable = this.riskService.getRiskTable().pipe(shareReplay());
  tableObservable.subscribe((res) => this.riskTable = res, (err) => {this.error = err;});
  return tableObservable;
}

getAllData() {
  let riskTable = this.getRiskTable();
  let risks = this.getAllRisks(); // should also return some observable

  forkJoin(riskTable, risks).subscribe(_ => {
    // all observables have been completed
  });
}

Note that I also added shareReplay which ensures that multiple subscriptions to the same observable do not result in multiple calls to your API end point. One result is shared between multiple subscriptions to the observable.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

Multiple Http requests called and stored in one array, but how to wait until all requests finish before working with array

Wait for function to finish running before iterating

How to wait for a jQuery toggle to finish before running another function?

Ionic 3 Wait for storage promise to completely finish before running function

Wait for multiple Alamofire Requests to finish

wait function to finish in Angular

Angular Wait for boolean function to finish

Wait multiple observable requests to finish using RXSwift

Wait for multiple simultaneous powershell commands in other sessions to finish before running next commands

Angular 5, rxjs- wait for observable to finish only if it is in a middle of a run before running another process

Wait for function to finish before calling it again

Wait for a function to finish before continuing in javascript

wait for for loop to finish before executing next function

How to wait for Function to finish before continuing

Wait for one function to finish before continuing?

How to Wait for Angular2 to Handle Dynamic Multiple Http Requests?

Angular wait for multiple http requests to complete and then fire the last one

Kotlin - wait for multiple LiveData to be observe before running function

wait http req unit finish angular (services)

Angular2 wait for multiple promises to finish

Observable wait for a function with multiple observable to finish

angular await does not wait for the function to finish

Angular - Wait for function call to finish, to proceed with code

Make an Angular function wait for the subscribe to finish

How to wait for a function for finish in angular 4?

Wait for all HTTP requests to finish in XCode UI tests?

Jest: Wait for an async test to finish before running the next one

Wait for download method to finish before running next .then - node.js

How to wait for a loop to finish running before sending back a response in NodeJs?