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

本小妞迷上赌 提交于 2019-12-11 06:07:16

问题


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


回答1:


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


来源:https://stackoverflow.com/questions/41028702/in-angular-how-to-handle-promise-reject-when-using-async-await

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!