问题
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