Promise 中的 setTimeout - 如何解决以及为什么它只运行一次?

setTimeout in a Promise - how to resolve and why does it only runs once?

我想根据随机时间模拟鼠标滚动,在 Promise 中使用 setTimeout。 我的目标是继续向下滚动到网页底部:应该重复调用 autoScroll 函数直到到达底部,然后解析 Promise。 目前代码只运行一次,然后出现 2 个错误: 未捕获的 ReferenceError:未定义 loopScroll(在浏览器的控制台中) UnhandledPromiseRejectionWarning(在 VSCode)。

async function loopScroll(page) { 
    await page.evaluate(async () => {
        await new Promise((resolve, reject) => {
            let rand = Math.round(Math.random() * (3000 - 500)) + 500;
            setTimeout(function () {
                function autoScroll() {
                    let scrollHeight = document.body.scrollHeight;
                    let currentHeight = 0;
                    let distance = 100;
                    window.scrollBy(0, distance);
                    currentHeight += distance;
                    if (currentHeight >= scrollHeight) {
                        resolve();
                    }
                }
                autoScroll();
                loopScroll(page);
            }, rand);
        });
    });
};

这个 Async - Promise 的东西让我有点困惑,我对它们没有太多经验,所以我真的不知道我做错了什么。 提前致谢。

如评论中所述,这里的第一个问题是这部分代码在NodeJS环境中运行:

 async function loopScroll(page) { 
   await page.evaluate(/* page environment */);
 }

那就是定义 loopScroll 的地方,页面环境无法访问该函数。这就是调用 loopScroll 失败并结束执行的原因。

因为您已经在使用 async / await,所以您根本不需要使用递归,只需 await 一个循环:

 await page.evaluate(async () => {
  const delay = ms => new Promise(resolve => setTimeout(resolve, ms));

  let scrollHeight = document.body.scrollHeight;
  let currentHeight = 0;
  let distance = 100;

  while(true) {
    let rand = Math.round(Math.random() * (3000 - 500)) + 500;

    window.scrollBy(0, distance);
    currentHeight += distance;
    if (currentHeight >= scrollHeight) {
         break;
    }

   await delay(rand);
 }
});