0

I have this:

private isLogged(): boolean {
    //check cookie here
    let logged: boolean;
    browser.manage().getCookies().then((cookies: IWebDriverOptionsCookie[]) => {
       if (cookies.length == 0) {
        console.log('Is Not Logged');
        console.log('My cookies', cookies);
        logged = false;
    });
    console.log('isLogged: ' , logged);
    return logged;
}

When I run this, the logged is:

   undefined

I go into the Is Not Logged and My cookies inside.

Am I missing sth or just tired and do not see simple mistake ?

Nitzan Tomer
  • 155,636
  • 47
  • 315
  • 299
Jerzy Gruszka
  • 1,629
  • 4
  • 15
  • 20
  • Your `logged` variable is assigned to asynchronously. It is logged before the promise has resolved. – Lee Aug 11 '16 at 11:07
  • What would be best to fix? – Jerzy Gruszka Aug 11 '16 at 11:10
  • Not 100% agree this is a direct duplicate. May be [this](http://stackoverflow.com/questions/29633969/value-of-a-function-in-javascriptprotractor-returns-as-undefined) or [this](http://stackoverflow.com/questions/38262804/protractor-getting-undefined-while-trying-to-return-a-value) or there multiple similar threads is/are a better fit. Do they all need to be closed, or is this a special topic? – alecxe Aug 11 '16 at 16:41

1 Answers1

0

When you call isLogged() function and return from it - the browser.manage().getCookies() promise has not yet been resolved - hence, the value of logged was never set.

Instead, let isLogged return a promise:

private isLogged(): boolean {
    return browser.manage().getCookies().then(function (cookies) {
      if (cookies.length == 0) {
        console.log('Is Not Logged');
        return false
      } else {
        console.log('Is Logged');
        console.log('My cookies', cookies);
        return true
      }
    });
}

And, resolve once the value is needed:

isLogged().then(function (isLogged) {
    console.log(isLogged);
});

To gain more understanding in promises in Protractor, please see Promises and the Control Flow documentation page.

alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195