then() 和 promise.success 一样吗?

Is then() the same as promise.success?

承诺模式方法:

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(){})

它们是一样的吗?

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

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

你把它弄得比需要的更复杂了,因为 $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); });

如 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 服务总是 return 的承诺,但在 1.4X 之前,您有 successerror 方法,它们是 promise.then(success, error).

除此之外,promise 符号确实更好,因为链接 promises 的力量,使用回调符号并不是那么优雅。类似于:

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

除此之外,您的实用程序服务应该 return de $http promise,您不需要 $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 函数可以使用数据。