繁体   English   中英

当 puppeteer 执行代码时,await 在循环内无法按预期工作 - 但在浏览器的控制台中运行时效果很好

[英]await does not work as expected inside a loop when the code is executed by puppeteer - but it works perfectly when run in browser's console

我正在使用 puppeteer 在浏览器中评估codeToBeEvaluated function codeToBeEvaluated有一个while循环,它应该在每 10 秒后显示一个alert (参见 B 行)。

问题是当我运行这个脚本时,我没有看到任何警报。 代码执行不会在 A 行等待 10 秒。而是进程立即退出。 我不知道为什么。 我真的很好奇为什么它不起作用。

有趣的是,当我在浏览器的控制台中仅运行codeToBeEvaluated function 时,它工作得非常好,并且我看到了我应该看到的警报。

如果有人可以解释这种行为,那就太棒了。 我不是在寻找任何解决方法来显示警报。 我只是想了解这种行为。

const puppeteer = require("puppeteer");


// this function will be executed in the browser
// it should create an alert after some time interval
const codeToBeEvaluated = async () => {
  let index_2 = 0;

  // a promise that resolves after ms*1000 seconds
  async function sleep(ms) {
    return new Promise((resolve) => {
      setTimeout(resolve, ms);
    });
  }

  // await within function's while loop
  async function whileWrapper() {
    while (index_2 < 10) {
      await sleep(10000); // LINE A: execution doesn't stop at all :/
      alert("hello " + index_2); // LINE B: does NOT execute at all
      index_2++;
    }
  }

  whileWrapper();
};

async function main(url) {
  const browser = await puppeteer.launch({
    // headless: false,
    devtools: true,
    // args: ["--no-sandbox", "--disable-setuid-sandbox"],
  });
  const page = await browser.newPage();

  await page.goto(url);

  await page.evaluate(codeToBeEvaluated);

  browser.close();
}

main("https://www.google.com/search?q=hello");

在 DevTools 上手动执行codeToBeEvaluated与从 puppeteer 脚本执行之间存在差异的原因是:

  • 在 DevTools 控制台上,脚本有无限的时间来执行更长的异步命令(除非您在浏览器仍在运行时快速关闭浏览器)
  • 在您的 puppeteer 脚本中,您在page.evaluate之后还有其他命令,例如browser.close (我建议您将其放在await之后,因为它返回 promise,),因此在 function 完成之前关闭浏览器

您还需要等待whileWrapper()的 promise ,因此将第 25 行中的代码更改为以下代码将使其行为符合您的预期:

  await whileWrapper();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM