制作一个返回远程数据并等待承诺完成的角度函数

时间:2016-07-04 02:22:39

标签: javascript angularjs promise

据我所知,等待远程数据的传统方式是来自promises但问题是我需要创建一个函数来返回由.then

创建的值。
//inside controller
$scope.someFunction = function(id){
   var returnVal;
   $http.post(someURL,{_id:id}).then(
       function(r){
           //lets assume r.data = {id:123,name:'john doe'}
           returnVal = r.data.name;
       },function(r){
           console.error(r.statusText);
           returnVal = 'error getting name'
       }    
   );
   return returnVal;
};

问题是它一直返回null结果,因为它甚至在没有调用.then时执行返回块。

//the html is like this
<main component>
    <!--this main component will generate dynamic number of subs-->
    <!--lets assume Seller is the main and sub is all the products he sold -->
    <sub component sub-detail="the function that returns correct value">
        <!--I need to make $http request to get the product details for each product generated-->
    </sub component>
</main component>
<another main component>
    <!--generates another series of subs-->
</another main component>

所以简而言之。我需要一个从http请求返回数据的函数()

1 个答案:

答案 0 :(得分:-2)

更新您的代码:

$scope.someFunction = function(id){
   var returnVal;
   return $http.post(someURL,{_id:id}).then(
       function(r){
           //lets assume r.data = {id:123,name:'john doe'}
           returnVal = r.data.name;
           return returnVal;
       },function(r){
           console.error(r.statusText);
           returnVal = 'error getting name';
           return returnVal;
       }    
   );
};