在 AngularJS 中使用带有 Promises 的成功/错误/最终/捕获
问题描述:
我在 AngularJs 中使用 $http
,但我不确定如何使用返回的承诺和处理错误.
I'm using $http
in AngularJs, and I'm not sure on how to use the returned promise and to handle errors.
我有这个代码:
$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?
答
Promise 是对语句的抽象,允许我们用异步代码同步表达自己.它们代表一次性任务的执行.
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.
它们还提供异常处理,就像普通代码一样,您可以从承诺返回,也可以抛出.
They also provide exception handling, just like normal code, you can return from a promise or you can throw.
您想要的同步代码是:
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.
});