所以,我想知道为什么我会看到这种特殊的行为。我不确定我是否不理解 Promise、JavaScript 或 Angular 的工作原理,但这就是发生的事情(我设置了这个 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>
我需要从 promise 中返回的内容中获取值。我认为最简单的方法是通过分配给 promise 对象之外的东西。如果您查看 plnkr,您会发现我通过分配给 $scope 变量或使用 angular.copy() 成功获取了值。但是,我无法成功直接分配给 defReuse() 函数中返回的变量,这很奇怪。我应该在这里添加,我已经声明了我试图在全局范围内分配给的 toBeRet 变量,并且结果相同。
所以,问题是为什么?关于 $scope 变量,我是否忽略了什么?或者 Angular 是如何工作的?或者 promise 如何发挥作用?目前这有点神秘..
最佳答案
Angular 中的
$q
帮助我们异步运行该函数。这个返回 promise ,一旦它解决了相应的 then
方法就会被调用。请通过以下一些链接来了解 Angular 中的 $q 和 Promise
关于javascript - AngularJS $q 和 promise 以及赋值困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33820026/