【问题标题】:Promise is not resolved when the condition is true (?)当条件为真时,承诺没有解决(?)
【发布时间】:2022-06-14 07:31:26
【问题描述】:

我无法理解为什么当条件为真时承诺没有得到解决。就我而言,我正在与 Puppeteer 合作,我正在尝试向下滚动以收取更多谷歌评论。我选择所有容器子项和评论总数。这是相同的数字,但似乎那个条件不是真的。我什么都不懂……

我的代码:

console.log('he entrado');

            await page.evaluate(() => new Promise((resolve) => {

                const scroller = document.querySelector('.review-dialog-list');
                const totalChilds = document.querySelectorAll('.gws-localreviews__general-reviews-block > *').length;
                const totalReviews = document.querySelector('.z5jxId').innerText.slice(0, -8);

                if(totalChilds != totalReviews){
                    var timer = setInterval(() => {
                        scroller.scrollBy(0, 400);
                    }, 100);
                }else{
                    clearInterval(timer);
                    resolve();
                }
            }));

            console.log('he salido');

我可以看到带有“He entrado”消息的 console.log,但它从不显示“He salido”。我的滚动条没有任何问题,我在浏览器控制台中检查了选择器,它们的值相同。

如果有人可以帮助我或向我解释我的代码失败的原因,我将不胜感激。希望你能理解我,如果没有,请告诉我,我会追加更多细节。非常感谢!

【问题讨论】:

  • resolveif 中的任何地方都有吗?
  • 你最后多了一个括号,去掉一个括号

标签: javascript puppeteer


【解决方案1】:

只有在page.evaluate 首次运行时,您才会检索scrollertotalChildstotalReviews。您应该在每次滚动时检索它们。

await page.evaluate(() => new Promise((resolve) => {
    const scroller = document.querySelector('.review-dialog-list');
    const timer = setInterval(() => {
        const totalChilds = document.querySelectorAll('.gws-localreviews__general-reviews-block > *').length;
        const totalReviews = document.querySelector('.z5jxId').innerText.slice(0, -8);
        if (totalChilds === totalReviews) {
            clearInterval(timer);
            resolve();
        }
        scroller.scrollBy(0, 400);
    }, 100);
}));

【讨论】:

  • 如果我得到正确...我只选择前十个孩子,这就是为什么我的条件不正确。我说的对吗?
  • 如果页面第一次加载时存在那十个,是的
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-08-20
  • 2023-01-21
  • 2022-01-16
  • 1970-01-01
  • 2019-01-25
相关资源
最近更新 更多