如何明确解决角$ q中的延期承诺?

时间:2015-10-22 23:22:25

标签: javascript angularjs

如果我的service喜欢

myServiceMethod: function(){
    $http.get(myUrl)
        .success(function(result){$q.defer().resolve(result);})
        .error(function(error){$q.defer().resolve(error);});

    return $q.defer().promise;
}

并在我的controller

myService.myServiceMethod()
    .then(function(result){})
    .then(function(error){});

有没有办法在名称空间中显式化?因为如果您开始嵌套延迟解决方案,似乎延迟的承诺会变得混乱。例如

myServiceMethod: function(){
    $http.get(myUrl)
        .success(
            function(result){
                if(result){
                    $q.defer().resolve(result);
                }else{
                    $q.defer().resolve(myCustomresult);
                }
        })
        .error(function(error){$q.defer().resolve(error);});

    return $q.defer().promise;
}

3 个答案:

答案 0 :(得分:2)

您正在创建过多的延迟对象,而返回的对象不是您正在解析或拒绝的对象

只返回本身返回承诺的$http。你想要做的是被认为是一种反模式

myServiceMethod: function(){
    // return the `$http` promise
    return $http.get(myUrl)
        .then(function(result){return result.data);})
         // either catch it here or catch in controller
        .catch(function(error){ alert('Error')});
}

控制器

myService.myServiceMethod()
    .then(function(result){})
    .catch(function(error){});

答案 1 :(得分:0)

每次调用$ q.defer(),你都会创建一个新的承诺,这不是正确的事情。

$http.get方法本身会返回一个promise,所以除非你正在做其他需要异步运行的东西,否则你不需要使用$ q

为了论证,你可以这样做:

myServiceMethod: function() {
 var myPromise =  $q.defer();
 $http.get(myUrl).success(function(result){
    if(result)
      myPromise.resolve(result);
    else
     myPromise.reject(result);
  });
return myPromise.promise;
}

答案 2 :(得分:0)

可能更短:

<强>服务

myServiceMethod: function () {
    return $http.get(myUrl).then(function (response) {
        return response.data || myCustomResult; // default result if API returned nothing
    });
}

<强>控制器

myService.myServiceMethod()
    .then(function (result) { /* do something ... */ })
    .catch(function (error) { /* handle error ... */ });
相关问题