这是“延迟反模式”吗?
是的。 当创建了一个新的冗余延迟对象以从promise链内部进行解析时,就会发生“延迟反模式” 。在您的情况下,您正在使用$
q为隐式返回承诺的内容返回承诺。您已经有一个Promise对象(
$http service它本身返回
promise),因此只需要返回它!
这是一个超简单的示例,它显示了具有延迟承诺和具有反模式的服务的样子,
这是反模式
app.factory("SomeFactory",['$http','$q']){ return { getdata: function(){ var deferred = $q.defer(); $http.get(destinationFactory.url) .then(function (response) { deferred.resolve(response.data); }) .catch(function (error) { deferred.reject(error); }); return deferred.promise; } }}])
这是你应该做的
app.factory("SomeFactory",['$http']){ return { getdata: function(){//$http itself returns a promise return $http.get(destinationFactory.url); }}而两者的消耗方式相同。
this.var = SomeFactory.getData() .then(function(response) { //some variable = response; },function(response) { //Do error handling here});这两个示例都没有错(至少在语法上)。但是第一个示例是多余的,并且不需要!
希望能帮助到你 :)



