【问题标题】:how to wait till a function to end to continue the code node js如何等到函数结束才能继续代码节点js
【发布时间】:2021-04-24 02:06:15
【问题描述】:

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

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

编辑:这里要明确的是,这是一个对时间非常敏感的操作,所以我不能做睡眠或等待或任何我需要它在完成后准确执行的操作。谢谢你

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

【问题讨论】:

标签: javascript node.js captcha webautomation


【解决方案1】:

您好,您可以执行 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 
}

希望对你有帮助

【讨论】:

    【解决方案2】:

    您可以使用 Promise 作为您的解决验证码的包装器,并且一旦用户指示它已经解决了验证码,或者我想您必须有某种方式知道用户已经解决了验证码,所以一旦您知道它,调用解析回调来执行后面的代码

    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 堆栈中执行,直到从我们的solvingCapcha 函数解决promise

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-09-23
      • 2019-05-22
      • 2018-06-06
      • 1970-01-01
      • 1970-01-01
      • 2018-06-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多