0

In es6 I need my promise to return true or false when done

This is my attempt but it returns a promise and I need it to be true or false

return this.isUserAuthenticated()
   .then(() => this.checkIfTeacherProfileExists());  

The return part needs to be true or false.

This is what one of the returns looks like:

  isUserAuthenticated = (): Promise<any> => {
    return new Promise((resolve, reject) => {  
        this.authService.checkIfLoggedIn().then((isAuthUser: boolean) => { 
            resolve(true); 
        });
    }); 
  }  
AngularM
  • 15,982
  • 28
  • 94
  • 169
  • 3
    *"but it returns a promise and I need it to be true or false"* Seems like you haven't understood the fundamentals of promises. Maybe have a look at https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise and https://www.promisejs.org/ . – Felix Kling Nov 05 '16 at 16:00
  • Also related: [How do I return the response from an asynchronous call?](http://stackoverflow.com/q/14220321/218196) – Felix Kling Nov 05 '16 at 16:03
  • People shouldn't use Promises until they understand the underlying problem being addressed. –  Nov 05 '16 at 16:05
  • I need to do 2 async calls and when they are done they then need to return true or false. Hows best to do this? – AngularM Nov 05 '16 at 16:11
  • @AngularM The others here have tried to say it but haven't gone into detail. If you are performing an asynchronous action, it is not possible to return `true` or `false` because your function will return _before_ the asynchronous action has completed. You can return a Promise for true/false, then the function that calls `isUserAuthenticated` needs to expect a promise to be the result, not a boolean. – loganfsmyth Nov 05 '16 at 19:13

1 Answers1

1

Your return is a promise holding true or false. So all you have to do is to chain another .then() which will hold the boolean.

return this.isUserAuthenticated()
   .then(() => this.checkIfTeacherProfileExists())
   .then(v => console.log(v)); // true or false  

Regarding your comment, see @FelixKling's comment - you can't do that, that's not how promises work.

baao
  • 71,625
  • 17
  • 143
  • 203