-1

I have to call HTTP. get function synchronously so that it will wait until its response didn't come. it should not go to execute next line until below line executes. Where I am wrong please help me out

this.classCheck.checkD().then(present => present ? console.log("Present==true  " + present) : console.log(" Present==false  " + present));

async checkD() {
    let present: boolean = true;
    let status : number;
    const res = await this.http.get(url,{ headers: header, observe:'response'}).toPromise().then( response => {
      console.log(response.status);
      status = response.status;
    });
    
    if(status >= 400) {
      present = false;
    }
    return present;
  }
  • 1
    Does this answer your question? [How do I return the response from an Observable/http/async call in angular?](https://stackoverflow.com/questions/43055706/how-do-i-return-the-response-from-an-observable-http-async-call-in-angular) – R. Richards Nov 14 '21 at 14:15
  • Actually, that one is not for synchronous calls it is just getting the response irrespective of the call sequence – Ritik Aggarwal Nov 14 '21 at 19:37

1 Answers1

0

You need to await on your promise. You or await or .then. One is synchronous, the other asynchronous.

async checkD() {
    let present: boolean = true;
    let status : number;
    const res = await this.http.get(url,{ headers: header, observe:'response'}).toPromise();
    status = res.status;
    if(status >= 400) {
      present = false;
    }
    return present;
}
Dharman
  • 30,962
  • 25
  • 85
  • 135
mikegross
  • 1,674
  • 2
  • 12
  • 27
  • This is giving an error. i think it is because we are extracting status from promise in the wrong way. – Ritik Aggarwal Nov 14 '21 at 17:10
  • Maybe, but this has nothing to do with your question. await a promise is done the way I showed you. Just console log res and you will see what you can do to follow – mikegross Nov 14 '21 at 18:20