使用成功/错误/终于/捕获与AngularJS承诺 [英] Using success/error/finally/catch with Promises in AngularJS
问题描述
我用 $ HTTP
在AngularJs,我不知道如何使用返回的承诺,来处理错误。我有这个code:
I'm using $http
in AngularJs, and I'm not sure on how to use the returned promise and to handle errors. I have this code:
$http.get(url)
.success(function (data) {
// Handle data
})
.error(function (data, status) {
// Handle HTTP error
})
.finally(function () {
// Execute logic independent of success/error
})
.catch(function (error) {
// Catch and handle exceptions from success/error/finally functions
});
这是一个很好的办法做到这一点,或者是有一个更简单的方法?
Is this a good way to do it, or is there an easier way?
推荐答案
承诺超过陈述,让我们的前preSS自己同步异步code的抽象。他们重新present的一次性任务的执行。
Promises are an abstraction over statements that allow us to express ourselves synchronously with asynchronous code. They represent a execution of a one time task.
他们还提供了异常处理,就像正常的code,你可以从一个承诺退货或你可以扔掉。
They also provide exception handling, just like normal code, you can return from a promise or you can throw.
你会在同步code要的是:
What you'd want in synchronous code is:
try{
try{
var res = $http.getSync("url");
res = someProcessingOf(res);
} catch (e) {
console.log("Got an error!",e);
throw e; // rethrow to not marked as handled
}
// do more stuff with res
} catch (e){
// handle errors in processing or in error.
}
该promisified版本很相似的:
The promisified version is very similar:
$http.get("url").
then(someProcessingOf).
catch(function(e){
console.log("got an error in initial processing",e);
throw e; // rethrow to not marked as handled,
// in $q it's better to `return $q.reject(e)` here
}).then(function(res){
// do more stuff
}).catch(function(e){
// handle errors in processing or in error.
});
这篇关于使用成功/错误/终于/捕获与AngularJS承诺的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!