javascriptangularrecaptcha-v3

wait for result before proceeding


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.


Solution

  • 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) {
        }
        
    }