1

I am writing a service which returns a function but the function doesn't return a value. Here is the code:

function getUser() {
    var Users = $resource('/api/users',{},{query: {method: 'get', isArray: true}});
    return Users.query({username:localStorage.getItem("token")}).$promise
}

function userrole() {
    var userrole='';

    var tmp=getUser();
    tmp.then(function(user){
        var userrole= user[0].role;
        console.log('The role is '+user[0].role);
        userrole=user[0].role;
        return userrole;
    });
    console.log('@ the end of userrole');
}

The function which doesn't return is userrole. I believe it's because of an async problem. How can I go about solving this?

danh
  • 62,181
  • 10
  • 95
  • 136
juliana Morales
  • 177
  • 3
  • 3
  • 10

2 Answers2

1

Not sure what you are trying to achieve but just return return tmp.then(... then when you will be able to call userrole().then((role) => ... ) from other place. Besides of that fix your indentations.

Maksym
  • 3,276
  • 3
  • 22
  • 27
  • 1
    What this answer means (correctly) is that the async function can't return the user role, it can/should return a promise to get the user role. – danh Dec 04 '16 at 20:44
  • @danh 10x and how on earth can i manipulate data from a query – juliana Morales Dec 04 '16 at 20:47
  • @julianaMorales What do you mean by manipulating data from the query? If the promise succeeds(like request) then when you can call `.then((dataReturnedFromPromise) => `. That's it, and if you chain `.then` callbacks then the next `then` function will return whatever you returned in the previous `.then` callback. – Maksym Dec 04 '16 at 21:01
1

If you use async methods in AngularJS (and in all Javascript) you need to use it always in functions above.

For example:

function getUser() {
  var token = localStorage.getItem('token');

  var Users = $resource('/api/users', {}, {
    query: {method: 'get', isArray: true}
  });


  return Users.query({username: token}).$promise;
}

function getUserRole() {
  return $q(function(resolve, reject) {
    getUser()
      .then(function(user){
        resolve(user[0].role);
      })
      .catch(reject);
  });
}

getUserRole().then(function (userRole) {
  console.log('The role is ' + userRole);
});
Danil Valov
  • 605
  • 1
  • 7
  • 16