0

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?

MrKekson
  • 720
  • 6
  • 18
  • `getUserName` can't return a user name, it can only return a promise for one. But you'd need to actually `return` that, returning from callbacks is not enough. – Bergi Dec 08 '15 at 16:51
  • I'll rewrite it to return a promise, but i do not understand, why return called before the previous log line? I think i'm missing something important here. – MrKekson Dec 08 '15 at 16:55

1 Answers1

0

You need to return the promise from the getUserName method

services.getUserName = function (id) {      
    return 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;
    });        
}
Raulucco
  • 3,406
  • 1
  • 21
  • 27