加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

在AngularJS中使用success/error/finally/catch与Promises

发布时间:2020-12-17 09:10:07 所属栏目:安全 来源:网络整理
导读:我在AngularJs中使用$ http,我不知道如何使用返回的promise和处理错误。 我有这个代码: $http .get(url) .success(function(data) { // Handle data }) .error(function(data,status) { // Handle HTTP error }) .finally(function() { // Execute logic i
我在AngularJs中使用$ http,我不知道如何使用返回的promise和处理错误。

我有这个代码:

$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
    });

这是一个很好的方法吗,还是有更容易的方法?

Promises是对语句的抽象,允许我们与异步代码同步表达自己。它们表示一次性任务的执行。

他们还提供异常处理,就像正常的代码,你可以从promise返回或你可以抛出。

在同步代码中你想要的是:

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版本非常相似:

$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.
});

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读