Question

I am using Recaptcha in Node.js and I am having some trouble with the scope of some boolean variables. Recaptcha will work if only I can figure this out. Also, I'm not using express.

If recaptcha was evaluated correctly, flag will be set to true in the function inside of simple_recaptcha. But when the function terminates, flag is false and is no longer true.

I am wondering if I can pass by reference to resolve this? Are there any other ways?

function processRecaptcha(response){
       ...got IP address ...
       ...set some variables ...
       flag = false; // I have tried both w/o var and with var

       simple_recaptcha(recaptcha_private_key, ip, challenge, response, function(err)    {
            if (err) {
               flag = false;
               console.log('recaptcha code: Incorrect. Flag is: ' + flag);
            }
            else{
               flag = true;
               console.log('recaptcha code: Correct. Flag is: ' + flag);
            }
      });
      console.log('Flag is: ' + flag);
      return flag;

}

Was it helpful?

Solution

Your function is working as it should (most likely), and you have this problem due to async nature of the simple_recaptcha call.

Your code does this:

  1. it sets the flag to false
  2. it then starts some function which will receive the callback (the simple_recaptcha() function)
  3. It then logs that the flag is false.

And sometimes later, when the simple_recaptcha is resolved, your flag is set to true. But the original function is by now returned.

Depending on your code and usage, you should be able to move the return flag; part somewhere inside the simple_recaptcha() callback function.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top