【问题标题】:Is then() the same as promise.success?then() 和 promise.success 一样吗?
【发布时间】:2023-03-17 15:27:01
【问题描述】:

承诺模式方法:

this.getData= function(url){
        var defer = $q.defer();

        $http({method: 'GET', url: url}).
            success(function(data, status){
                defer.resolve(data);
            })
            .error(function(data, status) {
                defer.reject(status);
            });

        return defer.promise;
    };

在控制器中调用它 -

utility.getData().then(function(){});

VS

promise = utility.getData();
promise.success(function(){})

它们都一样吗?

【问题讨论】:

  • stackoverflow.com/questions/23803743/what-is-the-explicit-promise-construction-antipattern-and-how-do-i-avoid-it

标签: angularjs promise angular-promise


【解决方案1】:

如 Angular 1.5 文档所述

The $http legacy promise methods success and error have been deprecated. Use the standard then method instead. If $httpProvider.useLegacyPromiseExtensions is set to false then these methods will throw $http/legacy error.

$http 服务始终返回承诺,但在 1.4X 之前,您拥有 successerror 方法,它们是 promise.then(success, error) 的快照。

除此之外,由于链式 Promise 的强大功能,Promise 表示法确实更好,使用回调表示法并不那么优雅。比如:

utility.getData().then(function(){
    return utility.getMoreData();
}).then(function(response){
    //do something if the data from second call
}).catch(function(err){
    //something was wrong with one of the calls
});

单次调用,你可能看不到任何优势,但 promise 确实可以很好地防止 de Callback-hell

除此之外,您的实用程序服务应该返回 de $http 承诺,您不需要 $q。比如:

this.getData= function(url){
    return $http({method: 'GET', url: url});
};

如果你真的想在调用前操作数据,你可以再次使用promise的力量:

this.getData= function(url){
    return $http({method: 'GET', url: url}).then(function(response){
        data = processData(response);
        return data;
    });
};

数据将可用于调用方的then 函数。

【讨论】:

  • 很好的答案!我实际上在这里遇到了一个相关问题 - stackoverflow.com/questions/36039450/…
  • 我编辑了答案,并对您的代码进行了一些调整
  • 问题出在那个问题的循环上。当我在 then 方法中执行 console.log(i) 时,我看到 i 值为 5,这是最大值。所以这导致只有我的范围数组的最后一个对象有一个值,但其余的对象是空的。那么你的解决方案能解决这个问题吗?
  • processData() 这里应该有什么?如何访问承诺数据?该服务返回一个 json 数组。
  • processData() 只是一个函数,您可以创建它来操作服务的响应返回给调用者(您的控制器)之前。服务的响应,即 json 数组,在 response 变量中。只是说清楚,通常你不需要做这个过程,所以你可以直接返回 $http(..);并在您的控制器中处理您的数据。此示例仅适用于您的控制器期望数据格式与服务返回的数据不同的情况。
【解决方案2】:

然后获取第二个可选函数参数,第一个成功执行,第二个失败:

promise.then(function () {
    // success
}, function (err) {
    // error
});

【讨论】:

  • 对,除此之外,他们做同样的事情吗? then 在 promise 成功时执行?
  • @Tisha 第一个函数在成功时执行,第二个在失败时执行
【解决方案3】:

因为$http 已经是 一个承诺,所以你不应该使用$q

this.getData= function(url){
    return $http({method: 'GET', url: url})
};


this.getData(urlToUse)
.then(function(res) {
    // do something with res.data 
})
.catch(function(err) { console.error(err); });

【讨论】:

  • 问题是 - 我称之为这个的地方,我也有一个问题。
  • utility.getData().then(function(){}).catch(function(status){});
  • @Tisha 和?这会如何改变事情?
  • 通常您的 getData 函数应该在服务中并从控制器调用
  • Simon,是的,我在主代码中就是这样做的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-11-22
  • 2015-10-18
  • 2014-04-06
  • 2017-11-29
  • 2021-04-14
  • 2020-06-04
  • 2017-12-22
相关资源
最近更新 更多