简体   繁体   中英

Async HTTP.get function asynchronously in angular

I have to call HTTP.get function asynchronously 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;
  }

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM