Curious about a particular behavior I'm witnessing. Unsure if there's a misunderstanding on my part regarding promises, JavaScript, or Angular. Here's what's happening (I've prepared a plnkr to demonstrate - 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>
Attempting to extract a value from a promise object. Thought the most straightforward method would be by assigning it to something outside the promise object. In the plnkr, you'll notice that I can successfully retrieve the value either by assigning to a $scope variable or using angular.copy(). However, I seem to face challenges when trying to assign directly to the variable returned in the defReuse() function. Curious indeed, especially since I've declared the toBeRet variable in the global scope with no difference in outcome.
The question is why? Am I missing something crucial about the $scope variable, how Angular operates, or the mechanics of promises? It's a bit of a puzzle at the moment...