【问题标题】:AngularJS - Promise vs then?AngularJS - Promise vs then?
【发布时间】:2015-04-03 01:02:43
【问题描述】:

我有 2 个问题 -

1) "success" 和 "then" 有什么区别? 示例 - $http.get(url).then 与 $http.get(url).success?

2) 承诺意味着将来会执行的东西,很好。我无法理解这与函数调用有何不同。当我们使用“$q.defer.resolve()”进行调用时,会执行一个 promise 调用。这不是函数调用吗?那么为什么这不能是一个普通的函数,并与任何其他函数调用(如 foo())一起执行呢?我是否错过了承诺所做的一些特别的事情! ?

【问题讨论】:

标签: angularjs promise


【解决方案1】:

“成功”和“那么”有什么区别?

then() 接受一个参数:http 响应对象。 success() 接受 4 个参数:响应的数据、响应的状态、响应的标头和 http 配置对象。当您只关心返回的数据时,success() 因此更易于使用。正如 New Dev 所说,返回的值是不同的:then() 为其回调返回的任何内容返回一个新的 Promise,并允许您返回一个新值,从而构建一个 Promise 链,而 success() 返回原始 Promise。

承诺意味着将来会执行的事情

不,不是真的。 Promise 是您现在执行某项操作的结果,但结果无法立即获得。由于 JavaScript 是单线程的,您不能只是阻塞并等待结果,因为这会完全冻结应用程序。因此,您只需注册一个回调函数,该函数将在结果可用时异步调用。例如:

$http.get('/some/url')

立即发送 HTTP 请求。但是要获得结果,我们需要等待字节传输到服务器,服务器处理请求并发送回响应,以及响应传输到浏览器。这可能需要几秒钟。所以 $http.get() 立即返回的是一个承诺:即一个代表未来结果的对象(或者,一旦收到结果,一个曾经是未来的结果)。

【讨论】:

    【解决方案2】:

    .then 返回一个新的承诺。

    .success 返回原始承诺。另一个区别是.success 获取response.data 作为输入参数,而.then 获取response

    这是how it's implemented

    promise.success = function(fn) {
       promise.then(function(response) {
          fn(response.data, response.status, response.headers, config);
       });
       return promise;
    };
    

    您可以使用.success(和.error)来处理$http 的相应结果,但不能修改数据或拒绝给予最终消费者的承诺(使用return $q.reject()$http 承诺。

    这是一个说明性示例,说明何时可以使用 .success vs/with .then

    return {
      getData: function(p1){
        return $http.get(url, {p1: p1})
                 .success($log.log) // can use generic functions since there is 
                 .error($log.error) // no requirement to return data
                 .then(function(response){
                    // here can massage the data into the output format
                    return response.data; 
                 });
    };
    

    我建议始终使用.then,因为它返回一个没有.success.error 处理程序的新承诺;这避免了 API 使用者使用 $http 特定的 .success/.error 的机会,从而无意中假设 $http 在幕后使用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-06
      • 1970-01-01
      • 2016-10-18
      • 1970-01-01
      • 1970-01-01
      • 2015-02-23
      相关资源
      最近更新 更多