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

时间:2016-12-07 22:43:10

标签: javascript angularjs async-await ecmascript-2017

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

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

1 个答案:

答案 0 :(得分:4)

如果拒绝承诺,则会引发错误。使用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
  }
}