简体   繁体   中英

Can I convert http client of Angular toPromise method into async and await?

I have an observable in my provider that is converted into promise by using the toPromise() method example below:

getAllProvinces() {
      return this.http.get(`assets/ph/provinces.json`).toPromise()
  }

and in my component I would use async and await to return the value asynchronously example below:

async getAllProvince() {
    try {
      const provinces = await this.registerApi.getAllProvinces
      console.log(provinces)
    } catch(e) {
      console.log(e)
    }
    // this.registerApi.getAllProvinces().then(response => this.provinces = response).catch(err => console.log(err))
  }

I also want to catch the error if something goes wrong.

Can someone shed some light for me convert my promise into async and await I still don't get the use of async and await I know it is just the evolution of promises .

Appreciate if someone could help. Thanks in advance.

So do this in

   getAllProvinces() {
    const promise = new Promise<any>((resolve, reject) => {
     this.http.get(`assets/ph/provinces.json`).toPromise()
        .then((res: string[]) => {
          resolve(res);
        })
        .catch(error => {
          reject(error);
        });
    });
    return promise;
  }

this will convert http request to promise in angular. Rest is same with just small change

async getAllProvince() {
    try {
      const provinces = await this.nameOftheService.getAllProvinces()
      console.log(provinces)
    } catch(e) {
      console.log(e)
    }

  }

this will work

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