Using async await on function with http post in it

#1

Hi, i have a function, which checks, if the url from input is correct url of api, that my app is communicating with. Code looks like this :

 checkCorrectUrl(url){
   return new Promise(resolve => {
     let headers = new Headers();
     headers.append('Content-Type', 'text/xml;charset=utf-8');
     headers.append('SOAPAction', '.....');
     var body = '.......';
     this.http.post(url+"/atws.asmx", body, {headers: headers}).timeout(3000).subscribe(data => {
         resolve(true);
       },(err)=>{
       resolve(false);
     });
   });
 }

I want to refactor it using async await, to make it cleaner, but somehow, it doesnt work. i tried it like this

  async checkCorrectUrl(url){
      let headers = new Headers();
      headers.append('Content-Type', 'text/xml;charset=utf-8');
      headers.append('SOAPAction', '....');
      var body = '.....';
      await this.http.post(url+"/atws.asmx", body, {headers: headers}).timeout(3000).toPromise().then(data => {
        return true;
        },(err)=>{
        return false;
      });
  }

but it doesnt wait for the http post and resolves … Any ideas what am i doing wrong?

#2

Hi @Vartex05 :wave:

In your example, you need to return the promise instead of awaiting it (return this.http.post...). You can also try this:

async checkCorrectUrl(url): Promise<boolean> {
  const headers = new Headers();
  headers.append('Content-Type', 'text/xml;charset=utf-8');
  headers.append('SOAPAction', '...');
      
  const body = '...';

  try {
    await this.http.post(`${url}/atws.asmx`, body, { headers }).timeout(3000).toPromise();
    return true;
  } catch (err) {
    return false;
  }
}

Best,
Rodrigo