在 Angular 中,如何在使用 async/await 时处理 promise reject

In Angular, how to handle promise reject when using async/await

在Angular中,如果我使用promise,代码将是

let promise = this.$resource('www.example.com.au/request.json').get().$promise
promise.then(data => {
    //promise solved
}, () => {
   //promise rejected
})

说到async/await 代码变为

async getData() {
    let data = await this.$resource('www.example.com.au/request.json').get().$promise
    this.localData = {...data}
}

但这只是为了解决承诺。如果承诺被拒绝,我该怎么办?谢谢

如果承诺被拒绝,将抛出错误。使用 try...catch:

async getData() {
  try {
    let data = await this.$resource('www.example.com.au/request.json').get().$promise
    this.localData = {...data};
  } catch(error) {
    // promise rejected
  }
}