在Angular中,如何在使用异步/等待时处理承诺拒绝

在Angular中,如何在使用异步/等待时处理承诺拒绝

问题描述:

在Angular中,如果我使用promise,则代码为

In Angular, if I use promise, the code would be

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

当涉及到异步/等待时 代码变成

when it comes to async/await the code becomes

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

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

but this is only for promise solved. if it is promise rejected, what should I do? thanks

如果诺言被拒绝,将引发错误.使用try...catch:

If the promise is rejected, an error will be thrown. Use 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
  }
}