4

I'm using Google's reCaptcha V3 as part of my Angular(7) project.

I would like to wait for the Token's response before proceeding to the rest of the code and before checking whether the Token is validated or not.

declare var grecaptcha: any;

  ngOnInit() {
    this.validateCaptcha();
    if(this.gToken)
    {
      ...
    }
  }
  gToken:string;
  validateCaptcha()
  {
    let self = this;
    grecaptcha.ready(function() {
    grecaptcha.execute('reCAPTCHA_site_key', {action: 'homepage'}).then(function(token){
      self.gToken = token;
    });
});
  }

The thing is that this.gToken is undefined because it doesn't wait to validateCaptcha to finish its job. I have also tried async and await but it didn't help. perhaps I used it wrongly.

JumpIntoTheWater
  • 1,306
  • 2
  • 19
  • 46

2 Answers2

7

You can use Promise here.

You need to wait until token generated.

You can also use async / await instead of Promise.

ngOnInit() {
   this.validateCaptcha().then(token => { // Here wait token generated
      if(token) {
      }
   })
}

validateCaptcha() {
    return new Promise((res, rej) => {
      grecaptcha.ready(() => {
              grecaptcha.execute('reCAPTCHA_site_key', {action: 
                 'homepage'}).then((token) => {
                  return res(token);
              })

      })
    })
}

Update example with async / await.

While using async / await the validateCaptcha method demonstrated above remains same (must return Promise)

async ngOnInit() {  // async keyword added here
    try {
        let token = await this.validateCaptcha();  // await keyword added here
        if(token) {
        }
    } catch(e) {
    }
    
}
Richardson. M
  • 852
  • 2
  • 17
  • 28
2

Why not have validateCaptcha() return a promise?

declare var grecaptcha: any;

  ngOnInit() {
    this.validateCaptcha().then(() => {
        if(this.gToken)
        {
          ...
        }
    });
  }
  gToken:string;
  validateCaptcha()
  {
    let self = this;
    return new Promise((resolve, reject) => {
        grecaptcha.ready(function() {
            grecaptcha.execute('reCAPTCHA_site_key', {action: 'homepage'}).then(function(token){
            self.gToken = token;
            resolve();
         });
       });
    });
  }
Keeleon
  • 1,352
  • 11
  • 14