2015-11-20 147 views
1

所以,我想知道为什么我看到这种特殊的行为。我不知道如果我不明白的东西有关的承诺是如何工作的,或JavaScript,或棱角分明,但在这里发生了什么(我有这个plnkr设立展示 - http://plnkr.co/edit/ZKXkUv?p=preview):

<html ng-app="queue"> 
<head> 
    <title>$q resolves for no one</title> 
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.7/angular.min.js"></script> 
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.7/angular-resource.js"></script> 
    <script> 
    angular.module('queue', ['ngResource']) 
     .controller('queueCtrl', ['$scope', '$q', function($scope, $q) 
     { 

     var _funk = true; 
     $scope.testing2; 

     var deferred = $q(function(resolve, reject) 
     { 
      if (_funk) { 
      resolve({funk: 'yes'}); 
      } else { 
      reject({funk: 'no'}); 
      } 
     }); 

     deferred.then(function(resolved){ 
      console.log(resolved.funk) 
     }, function(rejected){ 
      console.log(rejected); 
     }) 

     function defReuse() 
     { 
      var toBeRet = {}; 
      deferred.then(function(resolved){ 
      console.log('yea') 
      $scope.testing2 = resolved; 
      angular.copy(resolved, toBeRet); 
      }, function(rejected){ 
      toBeRet = rejected; 
      }) 
      return toBeRet; 
     } 

     $scope.testing = defReuse(); 

     }]); 
    </script> 
</head> 
<body ng-controller="queueCtrl"> 
    {{testing.funk}} 
    {{testing2.funk}} 
</body> 
</html> 

我需要从承诺中返回的内容中获得价值。我认为最简单的方法是通过分配承诺对象之外的东西。如果你看一下plnkr,你会看到我通过赋值给$ scope变量或者使用angular.copy()成功获取值。但是,我不能直接将其直接赋值给defReuse()函数中返回的变量,这很奇怪。我应该在这里添加我已经声明了我想要在全局范围中分配的toBeRet变量以及相同的结果。

那么,问题是为什么呢?有什么我忽略了$ scope变量?或者Angular如何工作?或承诺如何工作?目前有点神秘......

+0

答应到时候defReuse()执行,并返回toBeRet的toBeRet是空的。由于异步请求在后台不完整并且需要时间来填充toBeRet。 – Vivek

+0

@VVK这个答案的唯一问题是,如果我将全局范围中的变量更改为全局变量,并且只是指定但不返回,那么赋值仍然不会发生。另外,因为toBeRet在这方面是一个对象,所以应该引用它?所以,当承诺确实解决它应仍然分配给对象,并以这种方式到$ scope.testing变量,正确? –

+0

看着plnkr。它显示正确的结果。你推迟的成功函数返回** funk:“yes”**。并且您正在打印** testing.funk ** – Vivek

回答