在Angular中,如何在使用异步/等待时处理承诺拒绝 [英] In Angular, how to handle promise reject when using async/await
本文介绍了在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
}
}
这篇关于在Angular中,如何在使用异步/等待时处理承诺拒绝的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文