如何等到函数结束以继续代码节点js

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

所以我有一个验证码收割机,我手动解决验证码以获得验证码的令牌, 所以我想做的是等到我完成验证码并获取令牌并发送令牌并调用一个函数来完成结帐,这里发生的是在我完成验证码之前调用函数,例如代码(实在太长就不放了)

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();

长话短说,我希望在继续执行下一个函数之前先声明令牌变量

我想在验证码求解完成后执行的功能 提前谢谢你,抱歉缺乏解释技巧:p

编辑:在这里要明确这是一个非常时间敏感的操作,所以我不能做睡眠或等待或任何我只需要它在它之后执行的事情finished.Thank你

编辑 2:代码等待验证码收割机加载验证码,但不要等到我解决它。

你可以使用 promise 作为你的 solvingCaptcha 的包装器,一旦用户表明它已经解决了验证码,或者我想你必须有某种方式知道用户已经解决了验证码,所以一旦你知道,调用 resolve callback执行后面的代码

const SolvingCaptcha = function() {
   return new Promise((resolve, reject) => { 
   //solving captcha 
      if(captchaSolvedEvent) {
          token = "1234"
          token_list.push(token)
          resolve(); // this is the important part here, we are resolving means our work is done i.e captcha is solved, no need to call this until user solves the capcha
      }
   }
}

async function yourMainFunction() {
    await SolvingCaptcha();
    final_token=token_list[0]
    //puppeteer code.
    document.getElementById("g-recaptcha-response").innerHTML={final_token}
    checkoutJsonCall();
}

注意,如果你使用 await ,你必须让你的函数标记为 async ,这里 await 表示它下面的代码不会作为回调传递到 js 堆栈中执行,直到 promise 从我们的 solvingCapcha 函数解析

你好,你可以只做 while 循环来检查变量是否已定义,如果没有则设置超时。

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 
}

希望这对您有所帮助