1

How to stop execution until a condition evaluated, this code always return undefined:

function test() {
    var allGood;
    account.isUserAuthenticated().then(function(data) {
        if (data) {
            allGood = false;
        } else {
            allGood =  true;
        }
    });
    return allGood;
}
avck
  • 3,535
  • 3
  • 26
  • 38
newbie
  • 273
  • 2
  • 4
  • 13
  • 1
    What do you mean with "stop execution"? This function always returns `undefined` because it does not wait for `isUserAuthenticated` to return (that's why the use of a promise, I think) – Alberto Zaccagni Jun 02 '16 at 14:58
  • `function test() { return account.isUserAuthenticated().then(data => !data); }` – Bergi Jun 02 '16 at 20:27

1 Answers1

4

You are returning a result that is set inside of an asynchronous call (a promise) which means allGood is first returned (that's why it is undefined) and then sometime later it actually gets a value. What you should do instead is return the promise itself from your function:

function test() {
    return account.isUserAuthenticated().then(function(data) {
        if (data) {
            return false;
        } else {
            return true;
        }
    });
}

Then if you run:

test().then(function(allGood) {
  if (allGood) {
    // user is authenticated
  } else {
    // user is not authenticated
  }
});
nem035
  • 34,790
  • 6
  • 87
  • 99