I need some help with Angular and promises, since i'm definetley doing something wrong here:
var rootModule = angular.module('ims2Root',[]);
rootModule.controller('RootController', ['$q', '$scope', '$http', '$state', 'user', function ($q, $scope, $http, $state, user) {
$scope.title = "IMS2";
user.getUserList().then(function (data) {
console.log('loaded' , data.data);
console.log('fuuu', user.getUserName(1));
});
console.log('fooo', user.getUserName(1));
}]);
rootModule.factory('user', ['$q','$http', function ($q, $http) {
var services = {};
services.getUserList = function () {
return $http.get('/api/acc/getlist');
}
services.getUserName = function (id) {
this.getUserList().then(function (data) {
angular.forEach(data.data, function (val, key) {
if (data.data[key].id == id) {
console.log('found',val, data.data[key].userName);
return data.data[key].userName;
}
})
return 'not found:' + id;
});
}
return services;
}]);
output:
fooo undefined
loaded [Object { id=2, userName="icn36101"}, Object { id=3, userName="icn36115"}, Object { id=1, userName="icn36121"}]
fuuu undefined
found Object { id=1, userName="icn36121"} icn36121
found Object { id=1, userName="icn36121"} icn36121`
So my question is how come that the getUserName() console.log did get the string from the proper object, but it's function does return undefined.
In the getUserName() the return is right after the line logging the properly found value, so how come the console log in the function get called way after the return next line?