Search code examples
javascriptnode.jscaptchawebautomation

how to wait till a function to end to continue the code node js


so i have a captcha harvester that i solve captcha manually to obtain the token of the captcha, so what i want to do is to wait till I finish solving the captcha and get the token and send the token and call a function to finish the checkout, what happening here is the functions are being called before i finish solving the captcha for example in code(will not put the real code since it's really long)

SolvingCaptcha = function() {
  token = "1234"
  token_list.push(token)
}

final_token = token_list[0]

//puppeteer code.
await SolvingCaptcha();
document.getElementById("g-recaptcha-response").innerHTML = {
  final_token
}

checkoutJsonCall();

long story short I want the token variable to be declared before it continues to the next functions

the function that I want to execute after the captcha solving is completed thank u in advance and sorry for the lack of skills in explanation :p

EDIT: to be clear here it's a very time-sensitive operation so I cant do sleep or wait or anything I just need it to execute exactly after it finished.Thank u

EDIT 2 : the code wait till the captcha harvester to load the captcha, but don't wait until i solve it.


Solution

  • Hello,u can just do while loop that check the variable if its defined or yet and set a timeout if it didnt.

    const SolvingCaptcha = function() {
     
    function waitForElement(){
        tokenn = TOKEN_LIST[0]
    
        console.log(tokenn)
       while(typeof tokenn !== "undefined"){
            //variable exists, do what you want
        
            setTimeout(waitForElement,1500);//so this refreash every 1.5sec to check if to recheck if the tokenn is defined or yer 
        }
    }
     waitForElement();
      }
    
    
    const function2 = function(){
    
    solvingcaptcha();
    
    //what ever you want to do next 
    }
    

    hope this helps out