0

I need to wait an answer from my server to say if the email is already taken or not. But I'm struggling to make this synchronously. In my if statement, typescript says that isCorrectEmail() is a void function (that I can understand but cannot solve). Any idea?

isEmailAvailable(){

    return new Promise( (resolve, reject) => {

        this.authService.checkemail(this.user.email).then(result => {

                let res = <any> result; 
                if (res.code == 0){
                    resolve(true);
                }
                else resolve(false); 

              }, (err) => {
               reject(false);
        });

    });

};


isCorrectEmail(){

    this.isEmailAvailable().then( (result) => { return result ; } );

};


 checkPersonalInfos() 
 {
   if ( this.isCorrectEmail() == true){...}
   ..
 }
Jibeee
  • 822
  • 1
  • 11
  • 26
  • Avoid the [`Promise` constructor antipattern](https://stackoverflow.com/q/23803743/1048572?What-is-the-promise-construction-antipattern-and-how-to-avoid-it)! – Bergi Jun 08 '17 at 16:36

1 Answers1

0

You cannot turn an asynchronous call into a synchronous one.

You have two options: move the code which needs the use the resulting value entirely inside a then callback:

 checkPersonalInfos() 
 {
   this.isEmailAvailable().then(isAvailable => {
       if (isAvailable) { ... }
   }
 }

Or use the async/await syntax to make it look like synchronous code, but remember it is still asynchronous so other code will run during the await and if you return a result from the function it will be wrapped inside a Promise():

 async checkPersonalInfos() 
 {
   if (await this.isEmailAvailable()) { ... }
   ...
 }

You don't actually need your isCorrectEmail() function here as it does nothing at all to the result, but if it did something more complex so it was actually needed then it has to return the Promise:

isCorrectEmail(): Promise<boolean> {
    return this.isEmailAvailable().then(result => result);
};
Duncan
  • 92,073
  • 11
  • 122
  • 156