NodeJ异步等待未正确等待for循环

时间:2020-02-25 11:48:06

标签: node.js for-loop asynchronous async-await

我的异步函数内部有一个循环,该循环本质上是为了解决验证码,但是循环中的等待似乎不起作用...

这是循环的样子:

for(var i=0; i < 7; i++){
      fileName = `./tasks/myfile-${i.toString()}.json`

      // SOLVE reCAPTCHAs
      const requestId = await initiateCaptchaRequest(apiKey);
      const response = await pollForRequestResults(apiKey, requestId);
      console.log(`SOLVED CAPTCHA - ${response}`);

      // Should run this function AFTER the response has been received
      await enter(response);
}

这是循环用来解决验证码的函数的样子(代码来自:https://medium.com/@jsoverson/bypassing-captchas-with-headless-chrome-93f294518337):

async function initiateCaptchaRequest(apiKey) {
  const formData = {
    method: 'userrecaptcha',
    googlekey: siteDetails.sitekey,
    key: apiKey,
    pageurl: siteDetails.pageurl,
    json: 1
  };
  const response = await request.post('http://2captcha.com/in.php', {form: formData});
  return JSON.parse(response).request;
}

async function pollForRequestResults(key, id, retries = 30, interval = 1500, delay = 15000) {
  await timeout(delay);
  return poll({
    taskFn: requestCaptchaResults(key, id),
    interval,
    retries
  });
}

function requestCaptchaResults(apiKey, requestId) {
  const url = `http://2captcha.com/res.php?key=${apiKey}&action=get&id=${requestId}&json=1`;
  return async function() {
    return new Promise(async function(resolve, reject){
      const rawResponse = await request.get(url);
      const resp = JSON.parse(rawResponse);
      if (resp.status === 0) return reject(resp.request);
      resolve(resp.request);
    });
  }
}

const timeout = millis => new Promise(resolve => setTimeout(resolve, millis))

我的问题是,上面看到的循环应该运行 initialateCaptchaRequest 函数,该函数获取requestId, THEN 运行 pollForRequestResults 函数以获取响应并之后运行输入功能。

但是现在等待似乎没有工作,并且几乎在运行initializeCaptchaRequest函数之后立即运行,pollForRequestResults函数运行,该函数显然返回JSON解析错误,因为requestId尚未收集,并在requestCaptchaResults函数...

感谢您的帮助!

2 个答案:

答案 0 :(得分:0)

我试图重新创建您的问题,但对我来说似乎很好。但我认为问题出在 requestCaptchaResults 函数

(async ()=>{
 for(var i=0; i < 7; i++){
     await initiateCaptchaRequest(i);
     console.log(i)
 }
})()

function initiateCaptchaRequest(i){
  console.log('sdas'+i);
  return new Promise((resolve, reject)=>{
    setTimeout(()=>{resolve();}, 4000);
  });
}

输出:

sdas0
0
sdas1
1
sdas2
2
sdas3
3
sdas4
4
sdas5
5
sdas6
6

答案 1 :(得分:0)

await在for循环中不起作用,因为for循环不异步

所以您必须进行for循环承诺


const newFunc = ()=>{
     return new Promise(async (resolve,reject)=>{

        // SOLVE reCAPTCHAs
      const requestId = await initiateCaptchaRequest(apiKey);
      const response = await pollForRequestResults(apiKey, requestId);
      console.log(`SOLVED CAPTCHA - ${response}`);

      // Should run this function AFTER the response has been received
      const data = await enter(response);
      resolve(data);
     })
}

Yourfunction(){
val = []
for(var i=0; i < 7; i++){
       fileName = `./tasks/myfile-${i.toString()}.json`
      val.push(**your arguments)
}
return new Promise.all(val).then((res)=>{return res;}).catch((err)=> {return err;})

}