Search code examples
javascriptangularrestes6-promise

not waiting for data to be fetched from server on http get request angular


hi i have local server on port A and single web app on port 4200 server has some data i request via http

data.service.ts:

    export class DataService {
      constructor(private httpClient: HttpClient) {}

      async get_p() {
        return await this.httpClient.get<object[]>('/some api').toPromise();
      }

      async get_s() {
        return await this.httpClient.get<object[]>('/some api').toPromise();
      }
    }

in another ts file :

          init() {
            let p1 =this.dataService.get_s().then((result) => {this.s = 
             result; } ) ;
            let p2 = this.dataService.get_p().then((result) => {this.p = 
             result; } );

            Promise.all([p1, p2]).then(values => {
              console.log(values); ///undefined
            });

            console.log("not waiting for data");

well ther are error messages but they refer to the fact that both p and s are not intialized.

i have already checked that data comes ok from server by doing this requests in constructor and then i moved them to init function.

thank you


Solution

  • Your p1 and p2 promises don't have any resolved value because the .then() handlers assign result to this.s and this.p, but they don't return anything, therefore the resolved values for p1 and p2 are undefined. Remember, the return value from a .then() handler becomes the resolved value of the promise.

    Thus, when you do this:

    Promise.all([p1, p2]).then(values => {
        console.log(values); ///undefined
    });
    

    All values will be is an array of undefined. If instead, you do this:

    Promise.all([p1, p2]).then(values => {
        console.log(this.p, this.s);
    });
    

    you should see your values. Or, alternatively you can actually return those values from the .then() handlers and then each promise will have a resolved value.

          init() {
            let p1 =this.dataService.get_s().then((result) => {
                this.s = result; 
                return result;  // set resolved value of promise
            });
            let p2 = this.dataService.get_p().then((result) => {
                 this.p = result; 
                 return result;  // set resolved value of promise
            });
    
            Promise.all([p1, p2]).then(values => {
              console.log(values); // will show the resolved values now
            });