在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}
}
但这只是为了解决了承诺。如果承诺被拒绝,我该怎么办?感谢
答案 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
}
}