0

I have a factory that holds a variable user and simply returns it. If the value of user is undefined I ask the server for the value. I use an Ajax which returns a promise. But here I want the user or undefined if I get nothing from the server.

So basically the problem goes down to couple of lines:

function getUser() {
  if (user === undefined) {
    sessionAuthentication.restoreSession().then(function (r) {
      user = r;
    });
  }
  return user;
}

The code is basically wrong, because sessionAuthentication.restoreSession() returns a promise and I never wait for the result, just return the value.

However, I have no clue how to fix it. Basically I would say

wait 500ms for the promised result or just return undefined

but I just can not make it work.

Is there something wrong with this solution? Thanks!

Atais
  • 10,857
  • 6
  • 71
  • 111
  • 1
    You can't return from an asynchronous function, you have to wait until it's finished, and not with timeouts, but by using the provided callbacks, like `then` in your code. – adeneo Jan 28 '16 at 17:04
  • Just return that promise. – Bergi Jan 28 '16 at 19:01

0 Answers0