在 AngularJS 中使用带有 Promises 的成功/错误/最终/捕获 [英] Using success/error/finally/catch with Promises in AngularJS

查看:23
本文介绍了在 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.
});

这篇关于在 AngularJS 中使用带有 Promises 的成功/错误/最终/捕获的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆