Home > Software engineering >  Wait for Http Request to finish using NestJS
Wait for Http Request to finish using NestJS

Time:09-26

I'm using Angular NestJS as a combination here and I'm trying to fetch some data from public API. The case is that I can see the returned data from NestJS console but Angular-side returns empty JSON. The problem is that the frontend side won't wait for Http request to be finished and instead triggers console.log too early. I know that I need to wait for the response but how can I do so?

app.component.ts:

async listAnalyses() {
    await this.reportingService.listAnalyses().then(
        (data: any) => {
            console.log(data); // this is triggered too soon
        },
        (err: any) => {
            console.log(err);
        }
    )
}

reporting.service.ts:

listAnalyses() {
    return this.http.get(`${environment.api}/list-analyses`);
}

app.controller.ts:

 @Get('list-analyses')
 async listAnalyses() {
    let analyses;


    // params given here but hidden from the code (includes account data)
    await this.publicApi.listAnalyses(params, (err: any, data: any) => {
        if (err) {
            console.log(err);
        } else {
            console.log(analyses); // this logs real data in NestJS console, that's what I want in frontend side too
        }
    });

    return {
        analyses: analyses
    }
 }

How do I proceed from here?

CodePudding user response:

You need to convert a callback syntax into a Promise syntax (or Observable one).

 @Get('list-analyses')
 async listAnalyses() {
    return new Promise((res, rej) => this.publicApi.listAnalyses(
      params, (err: any, data: any) => {
        if (err) return rej(err);
        else return res(data);
      })
    );
 }
  • Related