使用AngularJS中的Promises成功/错误/ finally/catch

Joe*_*oel 111 promise angularjs angularjs-http

$http在AngularJs中使用,我不确定如何使用返回的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
    });
Run Code Online (Sandbox Code Playgroud)

这是一个很好的方法吗,还是有更简单的方法?

Ben*_*aum 101

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.
}
Run Code Online (Sandbox Code Playgroud)

宣传的版本非常相似:

$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.
});
Run Code Online (Sandbox Code Playgroud)

  • 你会如何使用`success()`,`error()`和`finally()`结合`catch()`?或者我必须使用`then(successFunction,errorFunction).catch(exceotionHandling).then(cleanUp);` (3认同)
  • @Joel一般来说,你不想使用`success`和`error`(更喜欢`.then`和`.catch`,你可以(并且应该)省略`.then`使用ac的`errorFunction` `catch`就像我上面的代码一样). (3认同)
  • @SirBenBenji $ q没有`.success`和`.error`,$ http返回一个$ q的承诺_添加了`success`和`error`处理程序 - 但是,这些处理程序不链,一般应该是如果/可能的话,避免 一般而言 - 如果您有疑问,最好将它们作为一个新问题提出,而不是作为对旧问题的评论. (3认同)

Mic*_*zos 42

忘记使用successerror方法.

两种方法都已在角度1.4中弃用.基本上,弃用背后的原因是它们不是可链接友好的,可以这么说.

通过以下示例,我将尝试演示我的意思success并且error不是可链接友好的.假设我们调用一个返回带有地址的用户对象的API:

用户对象:

{name: 'Igor', address: 'San Francisco'}
Run Code Online (Sandbox Code Playgroud)

致电API:

$http.get('/user')
    .success(function (user) {
        return user.address;   <---  
    })                            |  // you might expect that 'obj' is equal to the
    .then(function (obj) {   ------  // address of the user, but it is NOT

        console.log(obj); // -> {name: 'Igor', address: 'San Francisco'}
    });
};
Run Code Online (Sandbox Code Playgroud)

发生了什么?

因为success并且error返回原始的promise,即返回的$http.get那个,传递给它的回调的对象then是整个用户对象,也就是前面success回调的相同输入.

如果我们将两个链接起来then,那就不那么容易混淆了:

$http.get('/user')
    .then(function (user) {
        return user.address;  
    })
    .then(function (obj) {  
        console.log(obj); // -> 'San Francisco'
    });
};
Run Code Online (Sandbox Code Playgroud)


gre*_*pit 35

我认为以前的答案是正确的,但这是另一个例子(根据AngularJS 主页,只是fyi,success()和error()不推荐使用:

$http
    .get('http://someendpoint/maybe/returns/JSON')
    .then(function(response) {
        return response.data;
    }).catch(function(e) {
        console.log('Error: ', e);
        throw e;
    }).finally(function() {
        console.log('This finally block');
    });
Run Code Online (Sandbox Code Playgroud)

  • 据我所知,最后没有回复回复. (3认同)

jus*_*tin 11

您在寻找什么类型的粒度?您通常可以通过:

$http.get(url).then(
  //success function
  function(results) {
    //do something w/results.data
  },
  //error function
  function(err) {
    //handle error
  }
);
Run Code Online (Sandbox Code Playgroud)

我发现链接多个承诺时"最后"和"捕获"会更好.


zd3*_*333 5

在Angular $ http的情况下,success()和error()函数会将响应对象解包,因此回调签名就像$ http(...).success(function(data,status,headers,config))

对于then(),您可能会处理原始响应对象.比如发布在AngularJS $ http API文件中

$http({
        url: $scope.url,
        method: $scope.method,
        cache: $templateCache
    })
    .success(function(data, status) {
        $scope.status = status;
        $scope.data = data;
    })
    .error(function(data, status) {
        $scope.data = data || 'Request failed';
        $scope.status = status;
    });
Run Code Online (Sandbox Code Playgroud)

除非在先前的promise链中抛出新的错误,否则最后的.catch(...)将不需要.

  • 不推荐使用成功/错误方法. (2认同)