We are using an ancient (1.x) version of AngularJS. I am trying to use the outcome of a promise - but I can't seem to get the value. In the example I am providing here - you can see that I even tried using the global / window scope to store and later retrieve the value.
In previous versions I have tried var xxx and $scope.xxx, to the same result: I can't seem to access the content of my promise.
My code;
angular.module('surveyBuilder').controller('cloneUsersCtrl', cloneUsersCtrlFunction);
cloneUsersCtrlFunction.$inject = ['$http','$scope', '$state', '$stateParams', '$cookies', 'TenantHandler', 'Survey', 'TENANT', 'PERMISSION', 'Notification', '$log'];
function cloneUsersCtrlFunction($http, $scope, $state, $stateParams, $cookies, TenantHandler, Survey, TENANT, PERMISSION, Notification, $log) {
$scope.surveyId = $stateParams.surveyId;
$scope.selectedTenant = '' TenantHandler.getSelected();
$scope.canEdit = PERMISSION.edit;
$scope.activeOnly = false;
var getDatasources = function () {
return $http.get(apiBase 'tenants/' $scope.selectedTenant '/surveys/' $scope.surveyId '/cloneUsers');
}
getDatasources().then(function(data) {
console.log('data.data: line 439: ' data.data);
// Use the global WINDOW scope
window.gavinData = data.data;
console.log('window.gavinData: Line 442: ' window.gavinData);
});
console.log(window);
console.log('window.gavinData: Line 445:' window.gavinData);
And here is the console's output.
app.js:444 Window {... //clipped for succintness
app.js:445 window.gavinData: Line 445:undefined
app.js:439 data.data: line 439: 362,CUSTOMERFIRSTBANK daily email recipient data,363,Retail Banking Survey,371,Medibank Survey,383,Copy of Frequent Flyer Card Survey,404,DeplyTest,405,Petbarn Survey,406,Copy of Petbarn Survey
app.js:442 window.gavinData: Line 442: 362,CUSTOMERFIRSTBANK daily email recipient data,363,Retail Banking Survey,371,Medibank Survey,383,Copy of Frequent Flyer Card Survey,404,DeplyTest,405,Petbarn Survey,406,Copy of Petbarn Survey
In Chrome's Developer Tools, if I expand the Window object I can see the node for my data;
gavinData: (7) [Array(2), Array(2), Array(2), Array(2), Array(2), Array(2), Array(2)]
So why is it undefined at line 445? What do I need to do, to access the contents of the nested array?
Thanks!
CodePudding user response:
By the nature of promise, you don't know when it resolves(=when the then
part run).
First, getDatasources()
is executed, then sometime after, which nobody knows, it resolves. Meanwhile these lines below then
block
console.log(window);
console.log('window.gavinData: Line 445:' window.gavinData);
are executed. At this point, the promise may have been resolved, may have not.
CodePudding user response:
I have managed to work it out. My thinking was all wrong.
I had fallen into the trap of thinking that because I had a .then
- and code after the .then
call - that it made it automatically available to that later code - which is obviously wrong.